🛡️ NullReferenceException is the #1 Runtime Error
C# 8 introduces Nullable Reference Types. Compiler warns about potential nulls. Catch bugs at compile time.
📝 Enable Nullable
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
// In file
#nullable enable
❌ Without Nullable (Runtime Crash)
string name = GetName(); int length = name.Length; // 💥 NullReferenceException if name is null
✅ With Nullable (Compile Warning)
string? name = GetName(); int length = name.Length; // ⚠️ Warning: Possible null reference
🎯 Fixing Warnings
// Check for null
if (name != null)
{
int length = name.Length; // No warning
}
// Use null-conditional operator
int? length = name?.Length;
// Use null-coalescing
int length = name?.Length ?? 0;
// Return nullable
public string? FindName(int id) { }
// Non-nullable property must be initialized
public class User
{
public string Name { get; set; } = string.Empty; // Initialized
public string? Email { get; set; } // Optional
}
💡 Benefits
- Catch NullReferenceException at compile time
- Self-documenting API (string? vs string)
- Works with existing code (gradual adoption)
- Reduces runtime errors significantly
“Enabled nullable reference types. Compiler found 47 potential null bugs. Fixed them all. NullReferenceException crashes dropped 95%. Best C# 8 feature.”
