Nullable enablement

From dotnet/dotnet · View interactive version

Nullable enablement is an AI agent skill from the GitHub repository dotnet/dotnet. Enable C# nullable reference types on files that still have `#nullable disable` in the NuGet.Client codebase. Use this skill whenever the user asks to enable nullable, migrate nullable, remove `#nullable disable`, annotate nullability, or fix nullable warnings for any NuGet project or file. Also tri

How to use this skill

Skill file

Nullable Enablement Skill

This skill guides the process of enabling C# nullable reference types on files in the NuGet.Client repository that currently opt out with #nullable disable. The codebase has nullable globally enabled via build/common.project.props, so individual files opt out with #nullable disable at the top. Migration means removing that directive, annotating types correctly, and updating the public API surface files.

The work is inherently incremental — don't try to migrate an entire project at once. Work in batches of related files, fix cascading warnings, build, and repeat.

Coding Guidelines for Nullable Migration

Nullable migration is a rare chance to modernize internal types. Beyond just annotating, apply the immutability and non-null design principles from CODE0 — prefer required init over set, get-only collections, and readonly fields. The migration touchpoint is the natural moment to tighten up these types.

Fix Stale Contracts, Don't Paper Over Them

During nullable annotation you'll sometimes discover that a method's actual behavior doesn't match its documented contract — e.g., a method documented as "returns null if not found" that actually returns an empty object, or dead null checks in callers. Don't just annotate what the code does today. If the internal method's contract is wrong, fix it:

Annotation Philosophy: Prefer Non-Null

The default mindset when annotating is non-null unless proven otherwise. Before marking something ?, ask: "Can I make this non-null instead?" Sometimes a small, non-breaking code change can eliminate nullability — and that's preferable to marking something nullable. But be careful not to replace null problems with empty-value problems.

Good non-null opportunities:

When ? is the right answer:

The goal is to shrink the nullable surface area, but honestly — not by hiding nullability behind empty values that shift the bug downstream.

High-Level Workflow

  1. Identify target files — find files with #nullable disable in the target project.
  2. Pick a batch — group related files (e.g., a class and its immediate dependencies). Small batches (1–5 files) are easier to review.
  3. For each file:

a. Remove #nullable disable

b. Annotate types (parameters, return types, properties, fields)

c. Update PublicAPI.Shipped.txt for both TFMs

d. Fix cascading warnings in dependent files

  1. Build to verify zero warnings/errors.
  2. Repeat with the next batch.

Step-by-Step: Migrating a Single File

1. Remove the directive

Delete the #nullable disable line (and any blank line it leaves behind).

2. Annotate types

Work through every public and internal member with a non-null bias — look for opportunities to keep or make things non-null before reaching for ?:

3. Risk Assessment for Null Checks

When a parameter is annotated as non-null, the default is to add a runtime ArgumentNullException check if one doesn't already exist. Most of the time, this is the right thing to do:

Add the check (the common case):

NULL_INC — rare, last-resort escape hatch:

NULL_INC exists for the narrow case where a shipped public API parameter is practically never null, but you can't be 100% certain no caller passes null, and adding a throw would be a risky behavioral change. This should be very few instances across the entire codebase — if you're reaching for NULL_INC more than once or twice per PR, you're probably using it too liberally.

The criteria are strict — ALL of these must be true:

Place the NULL_INC as an XML <remarks> on the relevant property or as a comment on the constructor, using this format:

/// <remarks>
/// NULL_INC: Annotated as non-null but no runtime check is enforced in the constructor
/// to avoid introducing a new throw in a previously-permissive code path.
/// Revisit with telemetry to confirm callers never pass null.
/// </remarks>

If in doubt between adding a null check and using NULL_INC, add the null check. The bar for NULL_INC is intentionally high.

Never suppress nullability with ! (the forgiveness operator) when the value genuinely can be null. Make the type honest and let callers handle it.

4. Common Annotation Patterns

Constructor-initialized properties:

// Non-null — set in constructor, guaranteed by null check
public PackageIdentity Identity { get; }

// Nullable — no guarantee
public string? Description { get; set; }

required keyword for internal types:

// Prefer `required` over `null!` initializer for internal/private types
internal class Options
{
    public required string Path { get; init; }
}

TryCreate / TryGet patterns:

public bool TryGetValue(string key, [NotNullWhen(true)] out string? value)

Conditional member invariants:

When a boolean-returning method or property guarantees that a nullable member is non-null for a particular result, express that relationship with [MemberNotNullWhen]. This lets callers rely on the guard without weakening the member's honest nullable contract or using !.

[MemberNotNullWhen(true, nameof(DgSpecHash))]
public bool IsValid { get { return DgSpecHash != null; } }

Use the attribute only when every path returning the specified value establishes the member as non-null. Consider [MemberNotNull] when a method guarantees members are initialized after it returns, regardless of a boolean result.

Debug.Assert(x != null) + x!:

When the parameter type is non-null and all callers are nullable-enabled, you can remove both the assert and the ! — they're redundant.

Covariant return nullability:

A subclass method returning byte[] can override a base returning byte[]? — this is valid in C# 9+. Use it when the subclass guarantees non-null.

IEquatable and Equals:

public bool Equals(MyType? other)  // parameter is nullable
public override bool Equals(object? obj)  // always nullable

PublicAPI.Shipped.txt Updates

This is the most precision-sensitive part of the migration. Every public type and member has an entry in PublicAPI.Shipped.txt. Each project has two TFM directories (e.g., net8.0/ and net472/). Both must be updated identically.

The `~` (oblivious) prefix

Lines starting with ~ represent nullable-oblivious signatures. When you annotate a type, replace the ~ line in place with the correctly annotated line. Do NOT add to PublicAPI.Unshipped.txt.

Annotation syntax

| C# type | PublicAPI notation |

|---|---|

| string (non-null) | string! |

| string? | string? |

| byte[] (non-null) | byte[]! |

| byte[]? | byte[]? |

| string[] (non-null array of non-null strings) | string![]! |

| IEnumerable<PackageIdentity> (non-null) | System.Collections.Generic.IEnumerable<...PackageIdentity!>! |

| Task<bool> (non-null) | System.Threading.Tasks.Task<bool>! |

| Unconstrained generic T | T (NO ! — generics don't get annotated) |

| Func<T> (non-null) | Func<T>! (the Func gets !, not T) |

Rules

Example transformation

Before (oblivious):

~NuGet.Protocol.Core.Types.PackageDownloadContext.PackageDownloadContext(NuGet.Protocol.Core.Types.SourceCacheContext sourceCacheContext, string directDownloadDirectory, bool directDownload) -> void

After (annotated):

NuGet.Protocol.Core.Types.PackageDownloadContext.PackageDownloadContext(NuGet.Protocol.Core.Types.SourceCacheContext! sourceCacheContext, string? directDownloadDirectory, bool directDownload) -> void

Building and Verifying

After each batch of changes, build the affected project to ensure zero warnings/errors:

dotnet msbuild src\NuGet.Core\<ProjectName>\<ProjectName>.csproj -v:q

Also build the test projects to catch cascading warnings:

dotnet msbuild test\NuGet.Core.Tests\<ProjectName>.Tests\<ProjectName>.Tests.csproj -v:q
dotnet msbuild test\NuGet.Core.FuncTests\<ProjectName>.FuncTest\<ProjectName>.FuncTest.csproj -v:q

dotnet msbuild builds all TFMs without needing a restore step, unlike dotnet build which may fail on some TFMs with NETSDK1005 (missing restore for net8.0). Use dotnet msbuild as the default build command.

Common build errors after nullable migration:

| Error | Fix |

|---|---|

| RS0016 "Symbol not in PublicAPI" | You added a new annotated entry but didn't remove the ~ line — replace, don't add |

| RS0017 "Symbol removed" | You removed the ~ line but the replacement doesn't match — check annotation syntax |

| CS8600–CS8605 nullable warnings | Annotate the type correctly, or add a null check |

| CS8618 non-nullable field not initialized | Use required, add a constructor init, or make the field nullable |

XLF Files

Never edit .xlf files directly. They are generated from .resx files. If you need to change localized strings, edit the .resx file and build — the xlf files will be regenerated automatically.

Checklist Before Submitting

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.