Lesson 4 of 9
Nullable Reference Types & Null Safety
Nullable reference types (NRTs), enabled by default in .NET 6+ projects, make null-related bugs a compile-time error instead of a runtime NullReferenceException. This is critical for production ASP.NET Core APIs where NullReferenceException from unexpected nulls causes 500 errors.
Nullable Reference Types in Practice
// NRTs are enabled by default in .NET 6+ - in .csproj:
// <Nullable>enable</Nullable>
// ━━ Without NRT: NullReferenceException is possible at runtime ━━
// product.Name.ToUpper() → could crash if Name is null
// ━━ With NRT: compiler warns at the source ━━
public class Product
{
public required string Id { get; init; } // non-nullable: MUST be set
public required string Name { get; init; } // non-nullable: compiler ensures not null
public string? Description { get; init; } // nullable: explicitly opt-in to nullable
public decimal Price { get; init; }
public Category? Category { get; init; } // navigation property - nullable (may not be loaded)
}
// ━━ Null-conditional and null-coalescing operators ━━
public string GetCategoryName(Product product)
{
// ?. null-conditional: returns null instead of throwing
return product.Category?.Name ?? "Uncategorized";
}
// ━━ Null-forgiving operator ! - use sparingly, document why ━━
// Only use when YOU know it can't be null but compiler can't prove it
public void Process(string? input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
var upper = input!.ToUpper(); // ! tells compiler: trust me, it's not null here
// Better: just use input.ToUpper() after the null check - compiler narrows type
}
// ━━ Null checks with pattern matching (preferred) ━━
public async Task<IResult> GetProduct(string id, IProductRepository repo)
{
var product = await repo.FindByIdAsync(id);
// Pattern match null check - clean, compiler-friendly
if (product is null)
return Results.NotFound(new { Error = $"Product {id} not found" });
return Results.Ok(product); // compiler knows product is non-null here
}
interface IProductRepository { Task<Product?> FindByIdAsync(string id); }
record Category(string Name);Tip
Tip
Practice Nullable Reference Types Null Safety in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Nullable Reference Types Null Safety from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Nullable Reference Types Null Safety is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?