🛡️ Null Safety Made Easy
Null checks are verbose. Null-coalescing operators handle null elegantly. Provide defaults, chain checks, safe navigation.
❌ Verbose Null Checks
string name;
if (user != null && user.Name != null)
name = user.Name;
else
name = "Unknown";
✅ Null-Coalescing
string name = user?.Name ?? "Unknown";
📝 Null Operators
// Null-coalescing (??)
string name = user?.Name ?? "Unknown";
int age = user?.Age ?? 0;
double price = product?.Price ?? 0.0;
// Null-coalescing assignment (??=)
string name;
name ??= "Default Name"; // Only if null
// Null-conditional (?.)
string firstName = user?.Name?.FirstName; // Chain safely
int? orderCount = user?.Orders?.Count();
string street = user?.Address?.Street ?? "No address";
// Combining operators
string fullName = user?.FirstName?.ToUpper() ?? "Unknown";
string email = user?.Email?.Trim() ?? "No email";
// With nullable types
int? nullableAge = null;
int age = nullableAge ?? 25; // 25 if null
// With reference types
User? user = GetUser();
string name = user?.Name ?? "Guest";
// With Dictionaries
string value = dict?.GetValueOrDefault("key") ?? "default";
// With LINQ
var firstItem = list?.FirstOrDefault() ?? new Item();
🎯 Practical Examples
// Configuration
string apiKey = config["ApiKey"] ?? throw new Exception("ApiKey missing");
int timeout = int.Parse(config["Timeout"] ?? "30");
// Database operations
var user = await db.Users.FindAsync(id);
string displayName = user?.FullName ?? user?.Username ?? "Unknown User";
// API responses
var response = await httpClient.GetFromJsonAsync("...");
string token = response?.Data?.Token ?? "No token";
// Mapping
var dto = new UserDto
{
Id = entity?.Id ?? 0,
Name = entity?.Name ?? "Unknown",
Email = entity?.Email?.ToLowerInvariant() ?? "no-email",
CreatedAt = entity?.CreatedAt ?? DateTime.UtcNow
};
// Validation
string input = GetInput();
string sanitized = input?.Trim() ?? "";
// Event handling
string message = GetMessage() ?? "No message available";
// With arrays
string first = array?.FirstOrDefault() ?? "Empty";
// Complex chains
string result = data?.Items?.FirstOrDefault()?.Value?.ToString() ?? "No value";
✅ Benefits
- Cleaner and more concise code
- No null reference exceptions
- Safe navigation through chains
- Default values for nulls
- Improved readability
“Null-coalescing operators handle null elegantly. No more verbose checks. Essential for modern C#.”
