Lesson 2 of 13

Variables & Types

Learn C#'s value types, types and nullable types, and how var lets the work out types for you.

C#
// Value types (stored on stack)
int i = 42;
double d = 3.14159;
float f = 3.14f;
bool b = true;
char c = 'A';
decimal money = 99.99m;  // use decimal for financial calculations!
long big = 9_999_999_999L;

// Reference types (stored on heap)
string name = "Alice";
string? nullable = null;  // nullable reference type (C# 8+)

// var — type inference (compiler figures out the type)
var count = 10;         // int
var pi = 3.14;          // double
var greeting = "hello"; // string

// const and readonly
const int MaxRetries = 3;          // compile-time constant
readonly int instanceMax;          // set once in constructor

// String operations
string first = "Hello";
string combined = first + " World";
string interpolated = $"The answer is {42}";
string verbatim = @"C:\Users\Alice";  // no escape sequences
string multi = @"Line 1
Line 2
Line 3";

Console.WriteLine(name.Length);         // 5
Console.WriteLine(name.ToUpper());      // ALICE
Console.WriteLine(name.Contains("li")); // True
Console.WriteLine(name.Replace("i", "I")); // AlIce

// Nullable value types
int? maybeNull = null;
int value = maybeNull ?? 0;  // null-coalescing: use 0 if null
Console.WriteLine(value);    // 0

C# distinguishes between value types (int, double, bool, struct) and reference types (, , ). Value types are copied on assignment; reference types share the same underlying data.

C#
// Type conversion
int n = 42;
double d = n;              // implicit widening
int back = (int)3.99;      // explicit cast: truncates to 3
string s = n.ToString();   // int to string
int parsed = int.Parse("42");  // string to int (throws if invalid)
bool ok = int.TryParse("abc", out int result);  // safe parse
Console.WriteLine(ok);     // False

// Tuples (C# 7+)
(string name, int age) person = ("Alice", 30);
Console.WriteLine(person.name);  // Alice

var (n2, a2) = person;  // deconstruct
Console.WriteLine(n2);  // Alice
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.