C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Nullable Reference Types

C# Nullable Reference Types

Nullable reference types (C# 8+) make null-safety a compile-time feature, eliminating the billion-dollar mistake of NullReferenceException.

1 - Enabling

// In .csproj (recommended for all new projects)
<Nullable>enable</Nullable>

// Or per file
#nullable enable

2 - Non-Nullable vs Nullable

string  name  = "Alice"; // cannot be null — compiler enforces this
string? email = null;    // nullable — you must null-check before use

// Compiler warns here:
Console.WriteLine(email.Length); // warning: dereference of possibly null

// Safe access
Console.WriteLine(email?.Length ?? 0);
Console.WriteLine(email?.ToUpper() ?? "no email");

3 - Null-Forgiving Operator

string? maybeNull = GetValue();
// You know it is not null in this context:
string definitelyNotNull = maybeNull!; // tells compiler to trust you

4 - Null-Coalescing Assignment (C# 8)

string? cache = null;
cache ??= ComputeExpensiveValue(); // assign only if null
Console.WriteLine(cache);

5 - Required Members (C# 11)

public class User
{
    public required string Name  { get; init; }
    public required string Email { get; init; }
}

// Compiler error if Name or Email is missing:
var user = new User { Name = "Alice", Email = "[email protected]" };

Note: Enable nullable reference types in every new project. The compiler warnings pay for themselves many times over by catching null dereferences at development time rather than in production at 3 AM.

-Tip-