🛡️ No More NullReferenceException
NullReferenceException killing your app? Can’t tell if variable can be null? Nullable reference types (C# 8+) make nullability explicit. Compiler warns about potential null errors.
<PropertyGroup> <Nullable>enable</Nullable> </PropertyGroup> <!-- Or in specific files --> #nullable enable // At top of .cs file
❌ Before (Runtime crash)
public string GetName(int id)
{
var user = _repository.GetById(id);
return user.Name; // 💥 NullReferenceException!
}
No compiler warning. Crashes at runtime.
✅ After (Compile-time safety)
public string GetName(int id)
{
User? user = _repository.GetById(id);
if (user == null)
throw new UserNotFoundException(id);
return user.Name; // ✅ Safe!
}
Compiler warned that user could be null.
🎯 Nullable Syntax
// Non-nullable reference type (default) string name = "Alice"; name = null; // ⚠️ Warning: Cannot assign null // Nullable reference type (explicit ?) string? name = null; // ✅ OK name = "Alice"; // ✅ OK // Method signatures public User GetUser(int id) // Never returns null public User? FindUser(int id) // Might return null // Null-handling patterns string name = user?.Name ?? "Unknown"; User nonNullUser = user ?? throw new ArgumentNullException(nameof(user)); // Null-forgiving operator (! - use sparingly!) Console.WriteLine(user!.Name); // "I know it's not null"
🔧 Constructor and Property Initialization
// Using required (C# 11)
public class User
{
public required string Name { get; set; }
public string? Email { get; set; } // Optional, can be null
}
var user = new User { Name = "Alice" }; // ✅ OK
var invalid = new User { Email = "test@example.com" }; // ❌ Error: Name required
// Or default value
public class User
{
public string Name { get; set; } = string.Empty;
public List Orders { get; set; } = new();
}
💡 Migration Strategy
- Enable gradually: Per-file with #nullable enable
- Start with new code: Don’t rewrite everything at once
- Fix warnings systematically: Don’t suppress blindly
- Use analyzers: Enable all nullable warnings
- Team buy-in: Everyone must understand nullable
“Enabled nullable reference types on legacy codebase. Compiler found 147 potential null bugs. Fixed them all. NullReferenceException crashes dropped 95%. Best decision for code quality.”
