Dotnet Csharp Nullable Reference Types logo

Dotnet Csharp Nullable Reference Types

Community
wshaddix
dotnet-csharp-nullable-reference-types

Enabling nullable reference types. Annotation strategies, attributes, common agent mistakes.

Overview

Publisherwshaddix
Repositorydotnet-skills
Skill namedotnet-csharp-nullable-reference-types
Stars
79
Forks
13
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by wshaddix on GitHub. Read the source before you install it.

Installation

Install the Dotnet Csharp Nullable Reference Types AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wshaddix/dotnet-skills.git /tmp/dotnet-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-skills/skills/dotnet-csharp-nullable-reference-types .claude/skills/dotnet-csharp-nullable-reference-types
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Dotnet Csharp Nullable Reference Types in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Dotnet Csharp Nullable Reference Types on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Dotnet Csharp Nullable Reference Types is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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.

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> defaultNotes
net8.0+enable (in templates)New projects have NRT enabled by default
net6.0/net7.0enable (in templates)Same as net8.0
netstandard2.0/2.1not setMust opt in explicitly
net48 / oldernot setMust 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)

xml
<!-- In .csproj or Directory.Build.props -->
<PropertyGroup>
  <Nullable>enable</Nullable>
</PropertyGroup>

Per-File (Migration)

csharp
#nullable enable   // top of file -- enables NRT for this file only

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");
    }
}

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);
}

Common Attributes Summary

AttributeWhereMeaning
[NotNullWhen(true)]out parameterNon-null when method returns true
[NotNullWhen(false)]out parameterNon-null when method returns false
[MemberNotNull]methodNamed member is non-null after call
[MemberNotNullWhen(true)]methodNamed member is non-null when returns true
[NotNullIfNotNull]returnReturn is non-null if named param is non-null
[NotNull]parameterParameter is non-null after call (assertion)
[DoesNotReturn]methodMethod never returns (always throws)
[AllowNull]parameter/propertyCaller may pass null even if type is non-nullable
[DisallowNull]parameter/propertyCaller must not pass null even if type is nullable
[MaybeNull]return/outReturn may be null even if type is non-nullable
[MaybeNullWhen(false)]out parameterMay 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");

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";
}

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);
    }
}

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

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)

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
}

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

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)
}

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.


References

Frequently asked questions

What does the Dotnet Csharp Nullable Reference Types AI skill do?

Enabling nullable reference types. Annotation strategies, attributes, common agent mistakes.

Why use Dotnet Csharp Nullable Reference Types on TypingMind?

Because you install it once and use it with any model. Dotnet Csharp Nullable Reference Types is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Dotnet Csharp Nullable Reference Types in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/wshaddix/dotnet-skills/tree/master/skills/dotnet-csharp-nullable-reference-types. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Dotnet Csharp Nullable Reference Types?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Dotnet Csharp Nullable Reference Types?

As many as you like. As long as a model supports skills, you can use Dotnet Csharp Nullable Reference Types with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Dotnet Csharp Nullable Reference Types AI skill free?

It is published on GitHub by wshaddix. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇