dotnet-csharp-nullable-reference-types
БесплатноБез исполняемых скриптовНе проверенEnabling nullable reference types. Annotation strategies, attributes, common agent mistakes.
от wshaddix★ 94 звезды на GitHubОб этом скилле
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> 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>
Per-File (Migration)
#nullable enable // top of file -- enables NRT for this file only
Migration Strategy
For large codebases, enable NRT incrementally:
- Set
<Nullable>enable</Nullable>in the project - Add
#nullable disableat the top of every existing file (script or IDE tooling) - Remove
#nullable disablefile-by-file, fixing warnings as you go - Track progress: count remaining
#nullable disabledirectives
Annotation Patterns
Nullable and Non-Nullable
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:
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
| 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
// 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)
Установить dotnet-csharp-nullable-reference-types в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл dotnet-csharp-nullable-reference-types?
Enabling nullable reference types. Annotation strategies, attributes, common agent mistakes.
Как установить скилл dotnet-csharp-nullable-reference-types?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл dotnet-csharp-nullable-reference-types запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic