Pattern Matching & Nullables

Advanced 20 min read Lesson 11 of 13

Nullable Value Types

Declaring Nullables

int? age = null;
bool? isMember = null;
DateTime? birthDate = null;

Checking for Null

int? age = 25;

if (age.HasValue)
{
    Console.WriteLine($"Age: {age.Value}");
}

// Or using the value
if (age != null)
{
    Console.WriteLine($"Age: {age}");
}

Null-Coalescing Operator (??)

int? age = null;
int defaultAge = 18;

int actualAge = age ?? defaultAge; // 18

string name = null;
string displayName = name ?? "Guest"; // "Guest"

Null-Coalescing Assignment (??=)

List<string> names = null;
names ??= new List<string>(); // Creates new list if null

Pattern Matching

Type Pattern

object data = "Hello";

if (data is string text)
{
    Console.WriteLine($"Text length: {text.Length}");
}

if (data is int number)
{
    Console.WriteLine($"Number: {number}");
}

Switch Pattern Matching

public string GetDescription(object obj)
{
    return obj switch
    {
        int i => $"Integer: {i}",
        string s => $"String of length {s.Length}",
        DateTime d => $"Date: {d:d}",
        null => "Null value",
        _ => "Unknown type"
    };
}

Pattern Matching with Conditions

int score = 85;

string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

Console.WriteLine($"Grade: {grade}"); // B

Pattern Matching with Objects

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Person person = new Person { Name = "John", Age = 25 };

string description = person switch
{
    { Age: >= 18 } => $"{person.Name} is an adult",
    { Age: < 18 } => $"{person.Name} is a minor",
    null => "No person",
    _ => "Unknown"
};
Key Takeaway

Nullable types handle missing values safely. Pattern matching simplifies conditional logic and type checking.

Test Your Knowledge - Take Quiz