Mastering C# Part 2.1 Fundamentals
Fundamentals of C# programming Language

Now that we know how C# came to be and why it’s such a powerful language, it’s time to shift gears and dive into the essentials.
Let’s learn the fundamentals of C#!
From understanding basic syntax to writing your first program, we’ll build a solid foundation step by step. Ready to get started? Let’s jump right in and explore what makes C# so exciting!
Identifiers in C#
Identifiers are names given to program components like classes, methods, variables, and labels.
An identifier must:
Start with a letter (A-Z, a-z) or an underscore (
_).Be followed by letters, digits (0-9), or underscores.
Be case-sensitive (e.g.,
MyVariableandmyvariableare different).
Not be a keyword (reserved word in C#).
Keywords in C#
Keywords are reserved words with special meanings in C#.
These cannot be used as identifiers.
Examples:
int,class,public,for,while,if,else, etc.
Keywords have specific roles in the language and cannot be redefined.
Understanding Data Types in C#
C# is a strongly typed programming language, meaning every variable or constant must be explicitly defined with a data type. These types dictate the kind of data a variable can hold—be it integers, characters, or floating-point values. Here’s an overview of the key data types in C# to get you started:
Value Data Types
Value data types directly store their values in memory. These types are fast and efficient, as the variable holds the actual data. They also support both signed and unsigned literals, making them versatile. The base class for these types in C# is System.ValueType.
Signed vs. Unsigned Integers
Signed integers: Represent positive, negative, and zero values, offering a balanced range.
Unsigned integers: Exclusively store non-negative values, starting from zero up to a higher maximum range.
Common Value Data Types:
Integral Types: Store whole numbers, either signed (
int,long) or unsigned (uint,ulong).Floating Point Types: Handle numbers with fractional parts (
float,double).Decimal Types: Provide high precision for financial and monetary calculations (
decimal).Character Types: Store single characters (
char).Boolean Types: Represent true or false values (
bool).
using System;
namespace DataTypesDemo
{
class Program
{
static void Main()
{
// Character data type
char letter = 'A';
// Integer types
int age = 25;
short temperature = -10;
long distanceToMoon = 384400; // in kilometers
// Unsigned integer types
uint positiveCount = 100;
ushort portNumber = 8080;
ulong starsInGalaxy = 250000000000;
// Floating-point and decimal types
float piApproximation = 3.14f;
double gravity = 9.80665; // Earth's gravity in m/s^2
decimal bankBalance = 150000.75m;
// Boolean type
bool isActive = true;
// Display values with explanations
Console.WriteLine("Character Example: " + letter);
Console.WriteLine("Integer Example: " + age + " years old");
Console.WriteLine("Short Example: " + temperature + "°C temperature");
Console.WriteLine("Long Example: " + distanceToMoon + " km to the Moon");
Console.WriteLine("Unsigned Integer Example: " + positiveCount + " positive items");
Console.WriteLine("Unsigned Short Example: Port number is " + portNumber);
Console.WriteLine("Unsigned Long Example: Approx. " + starsInGalaxy + " stars in our galaxy");
Console.WriteLine("Float Example: Approximation of Pi is " + piApproximation);
Console.WriteLine("Double Example: Earth's gravity is " + gravity + " m/s²");
Console.WriteLine("Decimal Example: Bank balance is $" + bankBalance);
Console.WriteLine("Boolean Example: Is the system active? " + (isActive ? "Yes" : "No"));
// Byte example demonstrating overflow behavior
byte byteValue = 254;
Console.WriteLine("\\nByte Overflow Demonstration:");
Console.WriteLine("Initial byte value: " + byteValue);
byteValue++;
Console.WriteLine("After increment: " + byteValue); // Wraps to 255
byteValue++;
Console.WriteLine("After another increment: " + byteValue); // Wraps to 0
}
}
}
Understanding Reference Data Types in C
In C#, Reference Data Types store memory addresses rather than the actual value. Instead of holding data directly, they point to a location in memory where the data is stored. These types are foundational for managing complex data structures and objects in C#.
Built-in Reference Types:
String
Represents a sequence of Unicode characters.
Its fully qualified name is
System.String.Strings are immutable, meaning any modification creates a new instance in memory.
Example:
string greeting = "Hello, World!"; Console.WriteLine(greeting); // Output: Hello, World!
Object
The base class for all types in C# (
System.Object).All predefined and user-defined types, both value and reference types, inherit from
Object.It provides methods like
ToString(),Equals(), andGetHashCode().Boxing: Converting a value type to
object.Unboxing: Converting an
objectback to a value type.
Example:
// Boxing
int number = 42;
object boxedNumber = number; // The value type is boxed into an object
// Unboxing
int unboxedNumber = (int)boxedNumber; // The object is converted back to a value type
Console.WriteLine($"Boxed: {boxedNumber}, Unboxed: {unboxedNumber}");
Key Features of Reference Data Types:
Nullability: Reference types can be assigned
null, indicating no value or memory address.Memory Management: The garbage collector manages memory for reference types, automatically reclaiming unused memory.
Practical Considerations:
Use
stringfor textual data, ensuring type safety and immutability.Use
objectsparingly, as boxing/unboxing can affect performance. Prefer generics or specific types when possible for clarity and efficiency.
Variable
Variables in programming act as placeholders for storing and manipulating data that can change during runtime. They allow programs to handle different values entered by users or generated internally. Variables store information temporarily in the computer's memory (RAM) and can be accessed and modified as needed. They provide flexibility and dynamic behavior, enabling calculations and operations based on the changing values stored. Overall, variables are essential for working with varying data inputs and performing operations based on the stored information.
Compile time (default value if not initialised)
int y; default is 0;
Run time int num = Convert.ToInt32(Console.ReadLine());
Types of Variable
Variables in programming are placeholders for storing and manipulating data that can change during runtime. They are the basic units of storage in a program and must be declared before use. Variables can be categorized into different types such as local variables, instance variables, static variables, constant variables, and readonly variables.
- Local variables are defined within a block or method and have a limited scope within that block. They are created when the block is entered and destroyed when it is exited.
using System;
class Program
{
static void Main(string[] args)
{
// Local variable age
int age = 25;
Console.WriteLine("Age: " + age);
}
}
- Instance variables, also known as non-static variables, are declared in a class but outside any method or constructor. They are created when an object of the class is created and have separate copies for each object.
using System;
class Student
{
// Instance variables
string name;
int rollNumber;
static void Main(string[] args)
{
// Creating an object of Student class
Student student = new Student();
// Accessing instance variables
student.name = "John";
student.rollNumber = 123;
Console.WriteLine("Name: " + student.name);
Console.WriteLine("Roll Number: " + student.rollNumber);
}
}
- Static variables, or class variables, are declared with the static modifier and have only one copy per class, regardless of the number of objects created. They are initialized at the start of program execution and are accessible without creating an object.
using System;
class MathUtils
{
// Static variable
public static int result;
public static void Main(string[] args)
{
// Accessing static variable
MathUtils.result = 100;
Console.WriteLine("Result: " + MathUtils.result);
}
}
- Constant variables are declared with the const keyword and hold values that cannot be modified once declared. They must be initialized at the time of declaration.
using System;
class Constants
{
// Constant variable
public const double PI = 3.14159;
public static void Main(string[] args)
{
Console.WriteLine("PI Value: " + Constants.PI);
}
}
- Readonly variables are declared with the readonly keyword and can be assigned a value either during declaration or within the constructor. Once assigned, their values cannot be changed.
using System;
class Circle
{
// Readonly variable
public readonly double radius;
public Circle(double radius)
{
this.radius = radius;
}
public static void Main(string[] args)
{
Circle circle = new Circle(5.0);
Console.WriteLine("Radius: " + circle.radius);
}
}
Overall, variables provide flexibility and allow programs to handle changing data inputs and perform operations based on the stored information.
Implicit typed local variable-var
In C#, the
varkeyword is used to declare implicitly typed local variables. The type of the variable is inferred by the compiler based on the expression used to initialize it. Here's an example:using System; class Program { static void Main(string[] args) { var name = "John"; // Inferred type: string var age = 25; // Inferred type: int var isStudent = true; // Inferred type: bool Console.WriteLine("Name: " + name); Console.WriteLine("Age: " + age); Console.WriteLine("Is Student: " + isStudent); } }Using
varcan make the code more concise and improve readability in certain situations, especially when the type is obvious from the initializer. However, it's important to note that once the variable is declared withvar, its type becomes fixed and cannot be changed.It's worth mentioning that
varcan only be used for local variables within methods or blocks. It cannot be used for fields, method parameters, or return types.Dynamics variable
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.
Example:
dynamic value = 123;
Scope of the variable
The part of the program where a particular variable is accessible is termed as the Scope of that variable. A variable can be defined in a class, method, loop etc.
- Class Level Scope
Variables declared inside a class but outside any method have a class-level scope. They are accessible to all methods within the class.
class Example
{
int classLevelVariable = 10; // Class-level scope
void Display()
{
Console.WriteLine(classLevelVariable); // Accessible here
}
void Modify()
{
classLevelVariable += 5; // Accessible here too
}
}
- Method Level Scope
Variables declared inside a method are accessible only within that method.
class Example
{
void Display()
{
int methodLevelVariable = 20; // Method-level scope
Console.WriteLine(methodLevelVariable);
}
void AnotherMethod()
{
// methodLevelVariable is NOT accessible here
}
}
- Block Level Scope
Variables declared inside a block (e.g., {}) are only accessible within that block.
class Example
{
void Display()
{
if (true)
{
int blockLevelVariable = 30; // Block-level scope
Console.WriteLine(blockLevelVariable);
}
// blockLevelVariable is NOT accessible here
}
}
