Nullable reference types (C# 8+) make null-safety a compile-time feature, eliminating the billion-dollar mistake of NullReferenceException.
// In .csproj (recommended for all new projects)
<Nullable>enable</Nullable>
// Or per file
#nullable enable
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");
string? maybeNull = GetValue();
// You know it is not null in this context:
string definitelyNotNull = maybeNull!; // tells compiler to trust you
string? cache = null;
cache ??= ComputeExpensiveValue(); // assign only if null
Console.WriteLine(cache);
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]" };