🛡️ Nullable Reference Types = Null Safety
Null reference is #1 error. Nullable reference types prevent null bugs. Compiler help, fewer crashes, safer code.
❌ Null (Unsafe)
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}
// Potential null reference
✅ Nullable Reference (Safe)
public class User
{
public string Name { get; set; } = ""; // Not null
public string? Email { get; set; } // Can be null
}
// Compiler warns about nulls
📝 Enabling Nullable
# Project fileenable # Or per file #nullable enable # Disable nullable #nullable disable # Restore default #nullable restore # Global using // GlobalUsings.cs global using System; global using System.Collections.Generic; global using System.Threading.Tasks; # Nullable annotations public class Person { // Non-nullable (compiler warns if null) public string Name { get; set; } // Nullable (can be null) public string? Email { get; set; } // Constructor ensures Name not null public Person(string name) { Name = name; Email = null; } }
🎯 Working with Nullable
// Check for null
public string GetDisplayName(Person person)
{
// Null check required for nullable
if (person is null)
return "Unknown";
return person.Name;
}
// Null-forgiving operator
string name = person!.Name; // Assume not null
// Null-coalescing
string name = person?.Name ?? "Unknown";
// Null-coalescing assignment
person ??= new Person("Default");
// Pattern matching
if (person is null) { ... }
if (person is not null) { ... }
// Attributes
[NotNull]
[MaybeNull]
[DisallowNull]
// Required modifier (C# 11)
public class Product
{
public required string Name { get; init; }
public string? Description { get; init; }
}
// Factory method
public static Person Create(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Name required");
return new Person(name);
}
// Record with nullable
public record User(
string Name,
string? Email
);
// Generic constraints
public class Repository where T : class
{
public T? GetById(int id) { /* ... */ }
}
✅ Null Safety Benefits
- Compiler catches null bugs
- Fewer runtime crashes
- Better API design
- Clear intent (nullable or not)
- Improved code quality
“Nullable reference types prevent null bugs. Compiler assistance, safer code. Essential for robust C#.”
