csharp-nullability
Skill2 starsChanged 42 days agoMITView on GitHub
Use when writing or reviewing C# code that touches nullable reference types — enabling and trusting the `#nullable` analysis, the `System.Diagnostics.CodeAnalysis` attributes (`NotNullWhen`, `MaybeNullWhen`, `MemberNotNull`, `NotNull`, `AllowNull`, `DisallowNull`, `NotNullIfNotNull`), why `!` is usually wrong, guarding public boundaries, `required` interplay, generic `T?`/`notnull`, and `Try*` signatures.
In this repository56 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- benchmarkingSkill
- commit-messagesSkill
- csharp-15-syntaxSkill
- csharp-aot-trimmingSkill
- csharp-api-designSkill
- csharp-assembly-inspectionSkill
- csharp-asyncSkill
- csharp-collections-modernSkill
- csharp-concurrency-primitivesSkill
- csharp-data-layoutSkill
- csharp-debuggingSkill
- csharp-discardsSkill
- csharp-disposable-patternsSkill
- csharp-docsSkill
- csharp-error-handlingSkill
- csharp-extension-membersSkill
- csharp-generics-modernSkill
- csharp-guard-clausesSkill
- csharp-json-source-generationSkill
- csharp-language-versionsSkill
- csharp-logging-diagnosticsSkill
- csharp-lspSkill
- csharp-modern-typesSkill
- csharp-nullable-migrationSkill
- csharp-nunitSkill
- csharp-pattern-matchingSkill
- csharp-performanceSkill
- csharp-polyfillsSkill
- csharp-source-generatorsSkill
- csharp-static-lambdasSkill
- csharp-string-handlingSkill
- csharp-tunitSkill
- csharp-verificationSkill
- dispatching-subagentsSkill
- dotnet-11-librariesSkill
- dotnet-analyzersSkill
- dotnet-central-package-managementSkill
- dotnet-file-based-appsSkill
- dotnet-msbuild-usingsSkill
- dotnet-multi-targetingSkill
- dotnet-project-hygieneSkill
- dotnet-runSkill
- dotnet-runtime-asyncSkill
- dotnet-slnxSkill
- dotnet-test-platformsSkill
- executing-plansSkill
- performance-bounded-deduplicationSkill
- roslyn-analyzer-performanceSkill
- roslyn-discoverySkill
- roslyn-duplicate-detectionSkill
- roslyn-guard-rewritersSkill
- roslyn-rewritersSkill
- subagent-driven-developmentSkill
- tddSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 103
If you reach for ! because a warning is "annoying," that's a signal the surrounding code's contract is wrong — fix the contract (attribute …
- Very specific: line 157
Don't return a nullable value *and* a bool without the attribute — callers get an unnecessary warning (or worse, silently !-suppress it) at …
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Nullability — make the analysis tell the truth
Nullable reference types (NRT) are a compile-time contract, not runtime enforcement. The goal is to make the compiler's warnings accurate so a clean build means "no unhandled null" — that only works if you annotate honestly instead of silencing warnings.
Turn it on and mean it
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>enable applies to the whole project by default; use #nullable disable/#nullable restore directive pairs only around genuinely unconvertible legacy code, scoped as tightly as possible — never at the top of a new file.
A type is either string (the analysis believes it's never null here) or string? (it might be). The compiler tracks flow — after an if (x is null) return;, x is treated as non-null for the rest of that path — but it can only do that with the information you give it, which is what the rest of this skill is about.
The attributes — say what your method actually does
These live in System.Diagnostics.CodeAnalysis and describe null behavior the compiler can't infer from types alone.
[NotNullWhen(bool)] — an out/return value is non-null when the method returns the given bool. The standard shape for TryGetX:
bool TryParseName(string? input, [NotNullWhen(true)] out string? name)
{
if (string.IsNullOrWhiteSpace(input))
{
name = null;
return false;
}
name = input.Trim();
return true;
}
if (TryParseName(raw, out var name))
{
Console.WriteLine(name.Length); // no warning — NotNullWhen(true) proved it
}[MaybeNullWhen(bool)] — the opposite shape: a value declared non-null (T rather than T?) that is only possibly null when the method returns the given bool (common on TryGetValue-style APIs generic over T where you can't write T? for a reference-or-value-type parameter).
[MemberNotNull(nameof(field))] — a method guarantees a field/property is non-null after it returns, even though the compiler can't see that from the field's declared type alone. Use it on Init/setup helpers called from every constructor path:
class Widget
{
private string? _name;
[MemberNotNull(nameof(_name))]
void Init() => _name = "default";
public Widget()
{
Init();
Console.WriteLine(_name.Length); // no warning — MemberNotNull proved it
}
}[NotNull] (no When) — an out/ref parameter or return is always non-null when the method returns normally, regardless of what was passed in — typically paired with a parameter that arrives as T? and leaves guaranteed non-null (e.g., a validator that throws instead of returning on failure).
[AllowNull] / [DisallowNull] — decouple the get and set nullability of a property or parameter from its declared type. [AllowNull] string Name { get; set; } on a string-typed property means the setter accepts null (and normalizes it) while the getter still promises non-null:
private string _name = "";
[AllowNull]
public string Name
{
get => _name;
set => _name = value ?? "";
}[NotNullIfNotNull(nameof(param))] — the return is non-null whenever the named parameter was non-null (and may be null when it was null) — useful for pass-through/transform methods:
[return: NotNullIfNotNull(nameof(input))]
string? Normalize(string? input) => input?.Trim();! — the null-forgiving operator
! tells the compiler "trust me," permanently, with no runtime check. It's the right tool only when you have information the compiler cannot, and you're confident enough to accept an NullReferenceException if you're wrong:
// ✅ legitimate: framework guarantees non-null here, analyzer can't see it
var value = dictionary[key]!; // you just checked ContainsKey and nothing else can race
// ✅ legitimate: test/setup code establishing a known-good fixture
var service = _serviceProvider.GetService<IThing>()!; // registered in test setup, must exist
// ❌ silencing a warning without understanding it
var user = GetUser(id)!; // GetUser can genuinely return null — this just hides the bugIf you reach for ! because a warning is "annoying," that's a signal the surrounding code's contract is wrong — fix the contract (attribute it, guard it, or make the type honestly nullable) instead of suppressing the message.
Guard at public boundaries
Public API entry points should fail fast and loudly on invalid null, not rely on NRT warnings (which callers in other assemblies, or callers who ignore warnings, won't see):
public void Configure(string connectionString, Options options)
{
ArgumentNullException.ThrowIfNull(connectionString);
ArgumentNullException.ThrowIfNull(options);
ArgumentException.ThrowIfNullOrEmpty(connectionString);
// ...
}ArgumentNullException.ThrowIfNull(x) throws with the right parameter name (via CallerArgumentExpression) and is understood by the nullable analysis as a null check — code after it treats x as non-null. ArgumentException.ThrowIfNullOrEmpty/ThrowIfNullOrWhiteSpace do the same for strings that must also be non-empty.
required and nullability
required forces a member to be set during initialization, which is a different guarantee from non-nullability — a required string? member is still nullable, just mandatory to set (even if only to null). Use required for "must be provided", and the type's nullability for "may be null":
class Person
{
public required string Name { get; init; } // must be set, never null
public string? MiddleName { get; init; } // optional, may be null, not required
}For types a serializer fills, required also changes the wire contract. System.Text.Json throws when a required property is missing from the JSON, so don't add it just to satisfy the compiler. When unsure, make the member nullable and handle a missing value where the object is used (see csharp-nullable-migration and csharp-json-source-generation).
Generics: T? and notnull
- Unconstrained
T?in a generic method/type means "ifTis a reference type, this can be null; ifTis a value type,T?isNullable<T>." The compiler tracks both correctly, but it means you can't treatT?as uniformly "reference type made nullable" — checkdefault(T) is nullsemantics don't apply untilTis known. where T : notnullconstrainsTto non-nullable value types and non-nullable reference types — the standard constraint for dictionary keys and similar (Dictionary<TKey, TValue>itself constrainsTKey : notnull).where T : class/where T : structfurther narrow to reference/value types respectively, after whichT?behaves unambiguously as "nullable reference"/Nullable<T>.
static T Identity<T>(T value) where T : notnull => value;Try* pattern signatures
The idiomatic shape pairs a bool result with [NotNullWhen(true)] (or [MaybeNullWhen(false)] when the out type is T rather than T?) so callers get flow-sensitive non-null after checking the return:
public bool TryGetUser(int id, [NotNullWhen(true)] out User? user)
{
user = _cache.TryGetValue(id, out var found) ? found : null;
return user is not null;
}Don't return a nullable value and a bool without the attribute — callers get an unnecessary warning (or worse, silently !-suppress it) at every call site instead of getting flow analysis for free.
Checklist
<Nullable>enable</Nullable>project-wide;#nullable disableonly in tight, justified legacy pocketsTry*methods annotate theirout/return withNotNullWhen/MaybeNullWhen- Setup/init helpers that guarantee a field is non-null after returning use
[MemberNotNull] - Properties with asymmetric get/set nullability use
[AllowNull]/[DisallowNull]instead of widening the declared type - Pass-through/transform methods preserving null-in-null-out use
[NotNullIfNotNull] - Every
!has a one-line justification (in review, if not in a comment) — not a reflex to clear a warning - Public methods guard with
ArgumentNullException.ThrowIfNull/ArgumentException.ThrowIfNullOrEmpty, not just NRT warnings requiredused for "must be set", nullability used for "may be null" — not conflated- Generic code constrains
notnull/class/structwhere the algorithm actually depends on it
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

