2. Variables and Data Types

A variable is a named storage location with a type. C# is statically typed: the type is fixed at compile time and the compiler checks that you use it correctly. Variable names must start with a letter or underscore, may contain letters, digits and underscores, are case-sensitive and cannot be keywords. A variable must be assigned before it is read, and it exists only inside the block { } where it was declared (its scope).

Types fall into two families. Value types (int, double, bool, char, decimal, enum, struct) hold their data directly, and assigning one copies the value. Reference types (string, arrays, classes, List<T>) hold a reference to an object on the heap, so two variables can point to the same object. Whole numbers: byte (0 to 255), short, int (about ±2.1 billion), long (about ±9.2 quintillion), and the unsigned versions sbyte, ushort, uint and ulong. Fractional numbers: float (about 7 digits), double (about 15-16 digits) and decimal (28-29 digits, exact base-10, use it for money). Others: bool, char (one UTF-16 character) and string (text).

The var keyword lets the compiler infer the type from the value, and const declares a value that can never change. Convert between types with implicit conversions (safe, automatic), explicit casts (you accept possible data loss), the Convert class, and Parse / TryParse for text. Nullable value types (int?) can hold null, and enums give names to a fixed set of numeric constants.

Key points to remember

  • Use int for whole numbers, double for general measurements, decimal for money, bool for yes/no, string for text.
  • Literal suffixes: L = long, u = uint, f = float, m = decimal, d = double. Without a suffix a whole number is int and a fractional number is double, so 19.99m (not 19.99) is needed for a decimal.
  • Underscores make large numbers readable (1_000_000), 0x prefixes hexadecimal and 0b prefixes binary.
  • Default values: numbers 0, bool false, char '\0', reference types null. Local variables have no default and must be assigned before use.
  • const is fixed at compile time and is implicitly static; readonly (fields only) can be assigned once at run time in the constructor.
  • Integer arithmetic silently wraps around on overflow unless you use a checked context.
  • Value types are copied when assigned or passed; reference types share the same object. This is the cause of many beginner bugs.
  • Common mistake: int d = 5 / 2 gives 2, not 2.5. Use 5.0 / 2 or cast one side to double.
  • Prefer int.TryParse over int.Parse for user input: it returns false instead of throwing an exception.

Example 1: Declaring variables

C#
int age = 25;
double price = 19.99;
decimal balance = 1500.50m;
bool isActive = true;
char grade = 'A';
string name = "Thabo";
var count = 10;          // inferred as int
const double Pi = 3.14159;

Console.WriteLine($"{name} is {age} years old");
Show output Output
Thabo is 25 years old

Example 2: Ranges of the numeric types

C#
Console.WriteLine(byte.MaxValue);
Console.WriteLine(sbyte.MinValue);
Console.WriteLine(short.MaxValue);
Console.WriteLine(int.MaxValue);
Console.WriteLine(long.MaxValue);
Console.WriteLine(0.1 + 0.2);        // double is approximate
Console.WriteLine(0.1m + 0.2m);      // decimal is exact
Show output Output
255
-128
32767
2147483647
9223372036854775807
0.30000000000000004
0.3

Example 3: Literals: separators, hex, binary and suffixes

C#
int million = 1_000_000;
int hex = 0xFF;
int bin = 0b1010;
long big = 5_000_000_000L;
float f = 3.5f;
decimal d = 9.99m;
char letter = 'A';
char fromCode = (char)66;

Console.WriteLine(million);
Console.WriteLine(hex);
Console.WriteLine(bin);
Console.WriteLine(big);
Console.WriteLine(letter + " " + fromCode);
Show output Output
1000000
255
10
5000000000
A B

Example 4: Default values and scope

C#
Console.WriteLine(default(int));
Console.WriteLine(default(double));
Console.WriteLine(default(bool));
Console.WriteLine(default(string) is null);

int outer = 1;
{
    int inner = 2;                       // exists only inside this block
    Console.WriteLine(outer + inner);
}
// Console.WriteLine(inner);             // error: 'inner' does not exist here
Show output Output
0
0
False
True
3

Example 5: Type conversion

C#
int a = 7;
double b = a;               // implicit, safe
int c = (int)9.8;           // explicit cast, truncates
int d = int.Parse("42");    // string to int
bool ok = int.TryParse("abc", out int n);

Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(ok);
Show output Output
9
42
False

Example 6: The Convert class

C#
Console.WriteLine(Convert.ToInt32("123"));
Console.WriteLine(Convert.ToInt32(3.7));       // rounds
Console.WriteLine((int)3.7);                   // truncates
Console.WriteLine(Convert.ToString(255, 2));   // to binary text
Console.WriteLine(Convert.ToInt32("FF", 16));  // from hexadecimal text
Console.WriteLine(Convert.ToBoolean("true"));
Show output Output
123
4
3
11111111
255
True

Example 7: Overflow: unchecked and checked

C#
int big = int.MaxValue;

int wrapped = unchecked(big + 1);        // wraps around silently (default)
Console.WriteLine(wrapped);

try
{
    int safe = checked(big + 1);         // throws instead of wrapping
}
catch (OverflowException)
{
    Console.WriteLine("Overflow detected");
}
Show output Output
-2147483648
Overflow detected

Example 8: Value types and reference types

C#
int a = 5;
int b = a;          // copy of the value
b = 10;
Console.WriteLine(a);

int[] x = { 1, 2 };
int[] y = x;        // both variables point to the SAME array
y[0] = 99;
Console.WriteLine(x[0]);
Show output Output
5
99

Example 9: Enums

C#
Day today = Day.Tue;
Console.WriteLine(today);
Console.WriteLine((int)today);
Day parsed = Enum.Parse<Day>("Wed");
Console.WriteLine(parsed);
Console.WriteLine(Enum.TryParse("Sun", out Day d));   // false: not defined
foreach (Day v in Enum.GetValues<Day>())
    Console.Write(v + " ");

enum Day { Mon = 1, Tue, Wed }
Show output Output
Tue
2
Wed
False
Mon Tue Wed

Example 10: Tuples

C#
(string Name, int Age) person = ("Ann", 30);
Console.WriteLine($"{person.Name} is {person.Age}");

var (n, a) = person;                 // deconstruction
Console.WriteLine(n + a);

var point = (X: 3, Y: 4);
Console.WriteLine(point.X * point.Y);
Show output Output
Ann is 30
Ann30
12

Example 11: Nullable types

C#
int? score = null;
Console.WriteLine(score.HasValue);
Console.WriteLine(score.GetValueOrDefault());
score = 80;
Console.WriteLine(score ?? 0);
Console.WriteLine(score.Value);

string? nickname = null;                 // nullable reference type
Console.WriteLine(nickname?.Length ?? -1);
Show output Output
False
0
80
80
-1

Example 12: Boxing and type checks

C#
object o = 42;              // boxing: int stored as an object
int i = (int)o;             // unboxing
Console.WriteLine(o.GetType());
Console.WriteLine(o is int);
if (o is int n && n > 40)
    Console.WriteLine("Big int: " + n);
Show output Output
System.Int32
True
Big int: 42