dotnet-csharp-nullable-reference-types
Nullable reference type (NRT) annotation strategies, migration guidance for legacy codebases, and the most common
annotation mistakes AI agents make. NRT is enabled by default in all modern .NET templates (net6.0+), but many existing
codebases still need migration.
Scope
- NRT annotation strategies and nullable context configuration
- Migration guidance for legacy codebases
- Nullable attributes (MaybeNull, NotNull, etc.)
- Common AI agent NRT annotation mistakes
Out of scope
- Null-handling style (pattern matching, null-conditional) -- see [skill:dotnet-csharp-coding-standards]
- Pattern matching language features -- see [skill:dotnet-csharp-modern-patterns]
Cross-references: [skill:dotnet-csharp-coding-standards] for null-handling style, [skill:dotnet-csharp-modern-patterns]
for pattern matching with nulls.
Quick Reference: NRT Defaults by TFM
| TFM |
<Nullable> default |
Notes |
| net8.0+ |
enable (in templates) |
New projects have NRT enabled by default |
| net6.0/net7.0 |
enable (in templates) |
Same as net8.0 |
| netstandard2.0/2.1 |
not set |
Must opt in explicitly |
| net48 / older |
not set |
Must opt in explicitly |
Important: The TFM does not enforce NRT -- the <Nullable>enable</Nullable> MSBuild property does. Legacy projects
upgraded to net8.0 may not have it enabled.
Enabling NRT
Project-Wide (Recommended)
<!-- In .csproj or Directory.Build.props -->
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>
```csharp
### Per-File (Migration)
```csharp
#nullable enable // top of file -- enables NRT for this file only
```csharp
### Migration Strategy
For large codebases, enable NRT incrementally:
1. Set `<Nullable>enable</Nullable>` in the project
2. Add `#nullable disable` at the top of every existing file (script or IDE tooling)
3. Remove `#nullable disable` file-by-file, fixing warnings as you go
4. Track progress: count remaining `#nullable disable` directives
---
## Annotation Patterns
### Nullable and Non-Nullable
```csharp
public class UserService
{
// Non-nullable: must never be null
private readonly IUserRepository _repo;
// Nullable: explicitly may be null
public User? FindByEmail(string email)
{
return _repo.FindByEmail(email); // may return null
}
// Non-nullable parameter: caller must provide non-null
public async Task<User> GetByIdAsync(int id, CancellationToken ct = default)
{
return await _repo.GetByIdAsync(id, ct)
?? throw new NotFoundException($"User {id} not found");
}
}
```text
### Nullable Attributes
Use attributes from `System.Diagnostics.CodeAnalysis` to express nullability contracts the compiler cannot infer:
```csharp
using System.Diagnostics.CodeAnalysis;
// Output is non-null when method returns true
public bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
{
value = _dict.GetValueOrDefault(key);
return value is not null;
}
// Guarantees member is non-null after method returns
public class Connection
{
public string? ConnectionString { get; private set; }
[MemberNotNull(nameof(ConnectionString))]
public void Initialize(string connectionString)
{
ConnectionString = connectionString
?? throw new ArgumentNullException(nameof(connectionString));
}
}
// Return is non-null if input is non-null
[return: NotNullIfNotNull(nameof(input))]
public static string? Trim(string? input)
{
return input?.Trim();
}
// Parameter must not be null when method returns (for assertion methods)
public static void EnsureNotNull([NotNull] object? value, string paramName)
{
if (value is null)
{
throw new ArgumentNullException(paramName);
}
}
// Method never returns normally (always throws)
[DoesNotReturn]
public static void ThrowNotFound(string message)
{
throw new NotFoundException(message);
}
```text
### Common Attributes Summary
| Attribute | Where | Meaning |
| --------------------------- | ------------------ | -------------------------------------------------- |
| `[NotNullWhen(true)]` | `out` parameter | Non-null when method returns `true` |
| `[NotNullWhen(false)]` | `out` parameter | Non-null when method returns `false` |
| `[MemberNotNull]` | method | Named member is non-null after call |
| `[MemberNotNullWhen(true)]` | method | Named member is non-null when returns `true` |
| `[NotNullIfNotNull]` | return | Return is non-null if named param is non-null |
| `[NotNull]` | parameter | Parameter is non-null after call (assertion) |
| `[DoesNotReturn]` | method | Method never returns (always throws) |
| `[AllowNull]` | parameter/property | Caller may pass null even if type is non-nullable |
| `[DisallowNull]` | parameter/property | Caller must not pass null even if type is nullable |
| `[MaybeNull]` | return/out | Return may be null even if type is non-nullable |
| `[MaybeNullWhen(false)]` | `out` parameter | May be null when method returns `false` |
---
## Agent Gotchas
These are the most common NRT mistakes AI agents make when generating C# code.
### 1. Using `!` (Null-Forgiving Operator) to Silence Warnings
```csharp
// WRONG -- hides real null bugs
var user = _repo.FindByEmail(email)!; // will throw NRE if null
string name = user!.Name!; // double suppression is a red flag
// CORRECT -- handle null explicitly
var user = _repo.FindByEmail(email)
?? throw new NotFoundException($"User with email {email} not found");
```text
The `!` operator should only be used when you have knowledge the compiler cannot verify (e.g., after a debug assertion,
in test code with known data).
### 2. Ignoring Nullable Warnings
```csharp
// WRONG -- warning CS8602: Dereference of a possibly null reference
public string GetDisplayName(User? user)
{
return user.Name; // possible NRE!
}
// CORRECT
public string GetDisplayName(User? user)
{
return user?.Name ?? "Unknown";
}
```text
### 3. Wrong Nullability on Interface Implementations
```csharp
// Interface says nullable
public interface IRepository
{
User? FindById(int id);
}
// WRONG -- implementation changes contract
public class UserRepository : IRepository
{
public User FindById(int id) // removed nullable -- inconsistent
{
return _db.Users.First(u => u.Id == id);
}
}
// CORRECT -- preserve nullable contract
public class UserRepository : IRepository
{
public User? FindById(int id)
{
return _db.Users.FirstOrDefault(u => u.Id == id);
}
}
```text
### 4. Missing `[NotNullWhen]` on Try-Pattern Methods
```csharp
// WRONG -- compiler doesn't know result is non-null on success
public bool TryParse(string input, out Order? result)
{
// ...
}
// After call: result is still Order? even when method returned true
// CORRECT
public bool TryParse(string input, [NotNullWhen(true)] out Order? result)
{
// ...
}
// After call: result is Order (non-nullable) when method returned true
```text
### 5. Nullable Value Types vs Nullable Reference Types Confusion
```csharp
// These are different systems!
int? nullableInt = null; // Nullable<int> -- always existed
string? nullableStr = null; // NRT annotation -- compile-time only, no runtime type change
// typeof(int?) != typeof(int), but typeof(string?) == typeof(string)
```text
---
## Generic Constraints for Nullability
```csharp
// Constrain to non-nullable reference types
public class Repository<T> where T : class
{
public T Get(int id) => ...; // T is non-nullable
public T? Find(int id) => ...; // T? is nullable
}
// Allow both nullable and non-nullable
public class Cache<T> where T : notnull
{
public T GetOrDefault(string key, T defaultValue) => ...;
}
// Allow nullable type parameter (default)
public class Wrapper<T>
{
public T? Value { get; set; } // T? behavior depends on whether T is value or reference type
}
```text
---
## Collections and Nullability
```csharp
// Dictionary: value might not exist
Dictionary<string, User> users = new();
if (users.TryGetValue(key, out var user))
{
// user is non-null here (with proper NRT annotations in BCL)
}
// Array/List of nullable items
List<string?> names = ["Alice", null, "Bob"];
foreach (var name in names)
{
if (name is not null)
{
Console.WriteLine(name.Length); // safe
}
}
// Non-nullable collection with nullable lookup
IReadOnlyList<Order> orders = GetOrders();
Order? first = orders.FirstOrDefault(); // FirstOrDefault returns T? for reference types
```text
---
## EF Core and NRT
EF Core respects NRT annotations for required vs optional columns:
```csharp
public class Order
{
public int Id { get; set; }
public string CustomerName { get; set; } = ""; // NOT NULL column
public string? Notes { get; set; } // NULL column
public Address Address { get; set; } = null!; // Required navigation (EF convention)
}
```text
**Note:** `= null!` is acceptable for EF Core navigation properties where EF guarantees initialization. This is one of
the few valid uses of the null-forgiving operator.
---
## Code Navigation (Serena MCP)
**Primary approach:** Use Serena symbol operations for efficient code navigation:
1. **Find definitions**: `serena_find_symbol` instead of text search
2. **Understand structure**: `serena_get_symbols_overview` for file organization
3. **Track references**: `serena_find_referencing_symbols` for impact analysis
4. **Precise edits**: `serena_replace_symbol_body` for clean modifications
**When to use Serena vs traditional tools:**
- ✅ **Use Serena**: Navigation, refactoring, dependency analysis, precise edits
- ✅ **Use Read/Grep**: Reading full files, pattern matching, simple text operations
- ✅ **Fallback**: If Serena unavailable, traditional tools work fine
**Example workflow:**
```text
# Instead of:
Read: src/Services/OrderService.cs
Grep: "public void ProcessOrder"
# Use:
serena_find_symbol: "OrderService/ProcessOrder"
serena_get_symbols_overview: "src/Services/OrderService.cs"
```
## References
- [Nullable reference types (C# reference)](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references)
- [Attributes for null-state static analysis](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis)
- [Nullable reference type migration](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-migration-strategies)
- [.NET Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/)
1---2name: dotnet-csharp-nullable-reference-types3category: fundamentals4subcategory: coding-standards5description: Enables nullable reference types. Annotation strategies, migration, common agent mistakes.6license: MIT7targets: ['*']8tags: [csharp, dotnet, skill]9version: '0.0.1'10author: 'dotnet-agent-harness'11invocable: true12claudecode:13 allowed-tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit']14codexcli:15 short-description: '.NET skill guidance for csharp tasks'16opencode:17 allowed-tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit']18copilot: {}19geminicli: {}20antigravity: {}21---2223# dotnet-csharp-nullable-reference-types2425Nullable reference type (NRT) annotation strategies, migration guidance for legacy codebases, and the most common26annotation mistakes AI agents make. NRT is enabled by default in all modern .NET templates (net6.0+), but many existing27codebases still need migration.2829## Scope3031- NRT annotation strategies and nullable context configuration32- Migration guidance for legacy codebases33- Nullable attributes (MaybeNull, NotNull, etc.)34- Common AI agent NRT annotation mistakes3536## Out of scope3738- Null-handling style (pattern matching, null-conditional) -- see [skill:dotnet-csharp-coding-standards]39- Pattern matching language features -- see [skill:dotnet-csharp-modern-patterns]4041Cross-references: [skill:dotnet-csharp-coding-standards] for null-handling style, [skill:dotnet-csharp-modern-patterns]42for pattern matching with nulls.4344---4546## Quick Reference: NRT Defaults by TFM4748| TFM | `<Nullable>` default | Notes |49| ------------------ | ----------------------- | ---------------------------------------- |50| net8.0+ | `enable` (in templates) | New projects have NRT enabled by default |51| net6.0/net7.0 | `enable` (in templates) | Same as net8.0 |52| netstandard2.0/2.1 | not set | Must opt in explicitly |53| net48 / older | not set | Must opt in explicitly |5455**Important:** The TFM does not enforce NRT -- the `<Nullable>enable</Nullable>` MSBuild property does. Legacy projects56upgraded to net8.0 may not have it enabled.5758---5960## Enabling NRT6162### Project-Wide (Recommended)6364````xml6566<!-- In .csproj or Directory.Build.props -->67<PropertyGroup>68 <Nullable>enable</Nullable>69</PropertyGroup>7071```csharp7273### Per-File (Migration)7475```csharp7677#nullable enable // top of file -- enables NRT for this file only7879```csharp8081### Migration Strategy8283For large codebases, enable NRT incrementally:84851. Set `<Nullable>enable</Nullable>` in the project862. Add `#nullable disable` at the top of every existing file (script or IDE tooling)873. Remove `#nullable disable` file-by-file, fixing warnings as you go884. Track progress: count remaining `#nullable disable` directives8990---9192## Annotation Patterns9394### Nullable and Non-Nullable9596```csharp9798public class UserService99{100 // Non-nullable: must never be null101 private readonly IUserRepository _repo;102103 // Nullable: explicitly may be null104 public User? FindByEmail(string email)105 {106 return _repo.FindByEmail(email); // may return null107 }108109 // Non-nullable parameter: caller must provide non-null110 public async Task<User> GetByIdAsync(int id, CancellationToken ct = default)111 {112 return await _repo.GetByIdAsync(id, ct)113 ?? throw new NotFoundException($"User {id} not found");114 }115}116117```text118119### Nullable Attributes120121Use attributes from `System.Diagnostics.CodeAnalysis` to express nullability contracts the compiler cannot infer:122123```csharp124125using System.Diagnostics.CodeAnalysis;126127// Output is non-null when method returns true128public bool TryGetValue(string key, [NotNullWhen(true)] out string? value)129{130 value = _dict.GetValueOrDefault(key);131 return value is not null;132}133134// Guarantees member is non-null after method returns135public class Connection136{137 public string? ConnectionString { get; private set; }138139 [MemberNotNull(nameof(ConnectionString))]140 public void Initialize(string connectionString)141 {142 ConnectionString = connectionString143 ?? throw new ArgumentNullException(nameof(connectionString));144 }145}146147// Return is non-null if input is non-null148[return: NotNullIfNotNull(nameof(input))]149public static string? Trim(string? input)150{151 return input?.Trim();152}153154// Parameter must not be null when method returns (for assertion methods)155public static void EnsureNotNull([NotNull] object? value, string paramName)156{157 if (value is null)158 {159 throw new ArgumentNullException(paramName);160 }161}162163// Method never returns normally (always throws)164[DoesNotReturn]165public static void ThrowNotFound(string message)166{167 throw new NotFoundException(message);168}169170```text171172### Common Attributes Summary173174| Attribute | Where | Meaning |175| --------------------------- | ------------------ | -------------------------------------------------- |176| `[NotNullWhen(true)]` | `out` parameter | Non-null when method returns `true` |177| `[NotNullWhen(false)]` | `out` parameter | Non-null when method returns `false` |178| `[MemberNotNull]` | method | Named member is non-null after call |179| `[MemberNotNullWhen(true)]` | method | Named member is non-null when returns `true` |180| `[NotNullIfNotNull]` | return | Return is non-null if named param is non-null |181| `[NotNull]` | parameter | Parameter is non-null after call (assertion) |182| `[DoesNotReturn]` | method | Method never returns (always throws) |183| `[AllowNull]` | parameter/property | Caller may pass null even if type is non-nullable |184| `[DisallowNull]` | parameter/property | Caller must not pass null even if type is nullable |185| `[MaybeNull]` | return/out | Return may be null even if type is non-nullable |186| `[MaybeNullWhen(false)]` | `out` parameter | May be null when method returns `false` |187188---189190## Agent Gotchas191192These are the most common NRT mistakes AI agents make when generating C# code.193194### 1. Using `!` (Null-Forgiving Operator) to Silence Warnings195196```csharp197198// WRONG -- hides real null bugs199var user = _repo.FindByEmail(email)!; // will throw NRE if null200string name = user!.Name!; // double suppression is a red flag201202// CORRECT -- handle null explicitly203var user = _repo.FindByEmail(email)204 ?? throw new NotFoundException($"User with email {email} not found");205206```text207208The `!` operator should only be used when you have knowledge the compiler cannot verify (e.g., after a debug assertion,209in test code with known data).210211### 2. Ignoring Nullable Warnings212213```csharp214215// WRONG -- warning CS8602: Dereference of a possibly null reference216public string GetDisplayName(User? user)217{218 return user.Name; // possible NRE!219}220221// CORRECT222public string GetDisplayName(User? user)223{224 return user?.Name ?? "Unknown";225}226227```text228229### 3. Wrong Nullability on Interface Implementations230231```csharp232233// Interface says nullable234public interface IRepository235{236 User? FindById(int id);237}238239// WRONG -- implementation changes contract240public class UserRepository : IRepository241{242 public User FindById(int id) // removed nullable -- inconsistent243 {244 return _db.Users.First(u => u.Id == id);245 }246}247248// CORRECT -- preserve nullable contract249public class UserRepository : IRepository250{251 public User? FindById(int id)252 {253 return _db.Users.FirstOrDefault(u => u.Id == id);254 }255}256257```text258259### 4. Missing `[NotNullWhen]` on Try-Pattern Methods260261```csharp262263// WRONG -- compiler doesn't know result is non-null on success264public bool TryParse(string input, out Order? result)265{266 // ...267}268269// After call: result is still Order? even when method returned true270271// CORRECT272public bool TryParse(string input, [NotNullWhen(true)] out Order? result)273{274 // ...275}276277// After call: result is Order (non-nullable) when method returned true278279```text280281### 5. Nullable Value Types vs Nullable Reference Types Confusion282283```csharp284285// These are different systems!286int? nullableInt = null; // Nullable<int> -- always existed287string? nullableStr = null; // NRT annotation -- compile-time only, no runtime type change288289// typeof(int?) != typeof(int), but typeof(string?) == typeof(string)290291```text292293---294295## Generic Constraints for Nullability296297```csharp298299// Constrain to non-nullable reference types300public class Repository<T> where T : class301{302 public T Get(int id) => ...; // T is non-nullable303 public T? Find(int id) => ...; // T? is nullable304}305306// Allow both nullable and non-nullable307public class Cache<T> where T : notnull308{309 public T GetOrDefault(string key, T defaultValue) => ...;310}311312// Allow nullable type parameter (default)313public class Wrapper<T>314{315 public T? Value { get; set; } // T? behavior depends on whether T is value or reference type316}317318```text319320---321322## Collections and Nullability323324```csharp325326// Dictionary: value might not exist327Dictionary<string, User> users = new();328if (users.TryGetValue(key, out var user))329{330 // user is non-null here (with proper NRT annotations in BCL)331}332333// Array/List of nullable items334List<string?> names = ["Alice", null, "Bob"];335foreach (var name in names)336{337 if (name is not null)338 {339 Console.WriteLine(name.Length); // safe340 }341}342343// Non-nullable collection with nullable lookup344IReadOnlyList<Order> orders = GetOrders();345Order? first = orders.FirstOrDefault(); // FirstOrDefault returns T? for reference types346347```text348349---350351## EF Core and NRT352353EF Core respects NRT annotations for required vs optional columns:354355```csharp356357public class Order358{359 public int Id { get; set; }360 public string CustomerName { get; set; } = ""; // NOT NULL column361 public string? Notes { get; set; } // NULL column362 public Address Address { get; set; } = null!; // Required navigation (EF convention)363}364365```text366367**Note:** `= null!` is acceptable for EF Core navigation properties where EF guarantees initialization. This is one of368the few valid uses of the null-forgiving operator.369370---371372373374## Code Navigation (Serena MCP)375376**Primary approach:** Use Serena symbol operations for efficient code navigation:3773781. **Find definitions**: `serena_find_symbol` instead of text search3792. **Understand structure**: `serena_get_symbols_overview` for file organization3803. **Track references**: `serena_find_referencing_symbols` for impact analysis3814. **Precise edits**: `serena_replace_symbol_body` for clean modifications382383**When to use Serena vs traditional tools:**384- ✅ **Use Serena**: Navigation, refactoring, dependency analysis, precise edits385- ✅ **Use Read/Grep**: Reading full files, pattern matching, simple text operations386- ✅ **Fallback**: If Serena unavailable, traditional tools work fine387388**Example workflow:**389```text390# Instead of:391Read: src/Services/OrderService.cs392Grep: "public void ProcessOrder"393394# Use:395serena_find_symbol: "OrderService/ProcessOrder"396serena_get_symbols_overview: "src/Services/OrderService.cs"397```398## References399400- [Nullable reference types (C# reference)](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references)401- [Attributes for null-state static analysis](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis)402- [Nullable reference type migration](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-migration-strategies)403- [.NET Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/)404````