🛡️ 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.
The Null Problem
// Before nullable reference types
public class UserService
{
public string GetUserName(int userId)
{
var user = _repository.GetById(userId); // Could return null!
return user.Name; // 💥 NullReferenceException if user is null
}
}
// No compiler warning!
// Crashes at runtime
// "The billion dollar mistake" - Tony Hoare
Enable Nullable Reference Types
#nullable enable // At top of .cs file net8.0 enable
// After enabling nullable reference types
public class UserService
{
// Non-nullable: Must never be null
public string GetUserName(int userId)
{
User? user = _repository.GetById(userId); // User? = nullable
return user.Name; // ⚠️ Compiler warning: Possible null reference
}
// Fixed version
public string GetUserName(int userId)
{
User? user = _repository.GetById(userId);
if (user == null)
{
throw new UserNotFoundException(userId);
}
return user.Name; // ✅ No warning - null checked
}
// Or return nullable
public string? GetUserName(int userId)
{
User? user = _repository.GetById(userId);
return user?.Name; // ✅ Returns null if user is 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
// Non-nullable in method signatures
public void ProcessUser(User user) // user cannot be null
{
Console.WriteLine(user.Name); // ✅ No null check needed
}
// Nullable in method signatures
public void ProcessUser(User? user) // user might be null
{
if (user != null)
{
Console.WriteLine(user.Name); // ✅ Null checked
}
}
// Return types
public User GetUser(int id) // Never returns null
public User? FindUser(int id) // Might return null
Null-Handling Patterns
User? user = FindUser(123);
// 1. Null check
if (user != null)
{
Console.WriteLine(user.Name);
}
// 2. Null-conditional operator
Console.WriteLine(user?.Name); // Returns null if user is null
// 3. Null-coalescing operator
string name = user?.Name ?? "Unknown";
// 4. Throw if null
User nonNullUser = user ?? throw new ArgumentNullException(nameof(user));
// 5. Pattern matching
if (user is { Name: var name })
{
Console.WriteLine(name); // user is not null here
}
// 6. Null-forgiving operator (! - use sparingly!)
Console.WriteLine(user!.Name); // Tell compiler: "I know it's not null"
// Use only when you're 100% sure
Constructor and Property Initialization
public class User
{
// ⚠️ Warning: Non-nullable property must be initialized
public string Name { get; set; }
// ✅ Fixed: Initialize in constructor
public User(string name)
{
Name = name;
}
}
// Or use 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 user2 = 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();
}
🔧 Suppress Warnings (When Needed)
// Null-forgiving operator !
string GetName(User? user)
{
// You KNOW user is not null (e.g., validated earlier)
return user!.Name; // Suppresses warning
}
// Pragma directive (suppress for block)
#pragma warning disable CS8600 // Converting null literal
string? name = null;
#pragma warning restore CS8600
// Attribute (for methods that ensure non-null)
public static bool TryGetUser(int id, [NotNullWhen(true)] out User? user)
{
user = FindUser(id);
return user != null;
}
if (TryGetUser(123, out var user))
{
Console.WriteLine(user.Name); // ✅ Compiler knows user is not null
}
✅ Benefits
- Catch bugs early: At compile-time, not runtime
- Self-documenting: API clearly shows what can be null
- Better tooling: IDE shows nullable warnings
- Safer code: Forces you to handle null cases
- Fewer crashes: NullReferenceException reduced dramatically
💡 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
🎯 Real-World Example
#nullable enable
public class OrderService
{
private readonly IOrderRepository _repository;
private readonly IEmailService _emailService;
public OrderService(IOrderRepository repository, IEmailService emailService)
{
_repository = repository;
_emailService = emailService;
}
// Clear contract: Never returns null
public Order GetOrder(int id)
{
Order? order = _repository.FindById(id);
if (order == null)
{
throw new OrderNotFoundException($"Order {id} not found");
}
return order; // ✅ Guaranteed non-null
}
// Clear contract: Might return null
public Order? FindOrder(int id)
{
return _repository.FindById(id); // ✅ Nullable return
}
public async Task ProcessOrder(Order order, string? promoCode)
{
// order is non-nullable - no need to check
order.Status = OrderStatus.Processing;
// promoCode is nullable - must check
if (promoCode != null)
{
ApplyPromoCode(order, promoCode);
}
await _repository.SaveAsync(order);
// Email might be null, handle gracefully
await _emailService.SendConfirmationAsync(order.CustomerEmail ?? "no-reply@store.com");
}
}
“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.”

