04
Lesson 4 of 35 Β· Foundations

Variables & Data Types

Every piece of data in a C# program has a type. In this lesson you will learn the built-in value types, reference types, type inference with var, nullable types, and the difference between implicit and explicit conversions.

Value Types

Value types store their data directly. The most common ones are: int (32-bit integer), long (64-bit integer), double (64-bit floating point), float (32-bit floating point), decimal (128-bit high-precision), bool (true/false), and char (single Unicode character).

Value type examples ValueTypes.cs
int age        = 30;
long population = 8_100_000_000L;   // underscores aid readability
double pi      = 3.14159265358979;
float temp     = 36.6f;             // 'f' suffix for float
decimal price  = 19.99m;            // 'm' suffix for decimal
bool isOnSale  = true;
char grade     = 'A';

Console.WriteLine($"Age: {age}, Price: {price:C2}");

Reference Types

Reference types store a reference (pointer) to their data on the heap. The most important reference types are string, arrays, and objects (instances of classes). A reference type variable can be null, meaning it refers to nothing.

Type Inference with var

The var keyword tells the compiler to infer the type from the right-hand side of the assignment. The type is still staticβ€”it cannot change at runtime. Use var when the type is obvious from context; use explicit types when clarity matters.

var inference VarDemo.cs
var message = "Hello";          // inferred as string
var count   = 42;               // inferred as int
var items   = new List();// inferred as List

// NOT allowed β€” var requires an initialiser
// var x;  ← compile error

Nullable Types

Append ? to any value type to make it nullable: int? can hold an integer or null. Use the null-coalescing operator ?? to provide a default value, and the null-conditional operator ?. to safely call members.

Nullable example Nullable.cs
int? score = null;
Console.WriteLine(score ?? -1);       // prints -1

score = 95;
Console.WriteLine(score ?? -1);       // prints 95

string? name = null;
int len = name?.Length ?? 0;          // safe β€” len is 0

Type Conversion

An implicit conversion happens automatically when no data is lost (e.g. int β†’ long). An explicit cast is required when data might be lost (e.g. double β†’ int). The Convert class and Parse/TryParse methods handle string-to-type conversions safely.

Conversions Conversions.cs
int i = 100;
long l = i;             // implicit β€” safe
double d = 9.99;
int truncated = (int)d; // explicit cast β€” truncates to 9

string input = "123";
int parsed = int.Parse(input);              // throws if invalid
bool ok = int.TryParse("abc", out int val); // ok = false, val = 0