🛡️ Nullable Types = No More Null Reference
Null reference exceptions are the #1 bug. Nullable reference types catch them at compile time.
📝 Nullable Types Overview
// Enable nullable reference types
#nullable enable
// Non-nullable (must be set)
public string Name { get; set; }
// Nullable (can be null)
public string? Description { get; set; }
// Constructor with validation
public User(string name)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Name = name; // Non-nullable assignment
}
// Nullable parameters
public void Process(string? data)
{
if (data != null)
{
// data is not null here
Console.WriteLine(data.Length);
}
}
// Null-coalescing operator
var result = GetData() ?? "Default";
var length = GetData()?.Length ?? 0;
// Null-forgiving operator (use sparingly!)
string value = GetNullableData()!; // Assert not null
🎯 Advanced Patterns
// Pattern matching with null
public string GetDisplayName(User? user) => user switch
{
null => "Guest",
{ Name: var name } when string.IsNullOrEmpty(name) => "Anonymous",
_ => user.Name
};
// Nullable value types
int? age = GetAge();
if (age.HasValue)
{
Console.WriteLine(age.Value);
}
// TryParse pattern
if (int.TryParse(input, out int result))
{
// result is not null
}
// Property with null check
private string? _email;
public string Email
{
get => _email ?? throw new InvalidOperationException("Email not set");
set => _email = value ?? throw new ArgumentNullException(nameof(value));
}
// Generic nullability
public T? GetOrDefault<T>(T? value, T? defaultValue) where T : class
{
return value ?? defaultValue;
}
// Disable nullable warnings
#nullable disable
// Legacy code here
#nullable restore
💡 Nullable Type Tips
- Enable nullable globally
- Use ? for nullable types
- Use ?? for defaults
- Use ?. for safe navigation
- Validate input parameters
Nullable reference types eliminate the billion-dollar mistake. They make C# safer and more reliable.
