Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

csharp-nullable-types

БесплатноБез исполняемых скриптовНе проверен

Use when C# nullable reference types, null safety patterns, and migration strategies. Use when ensuring null safety in C# code.

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

C# Nullable Types

Master nullable reference types, null safety patterns, and migration strategies in C# 8+. This skill covers nullable value types, nullable reference types, null-safety annotations, operators, and best practices for writing null-safe code.

Nullable Reference Types (C# 8+)

Nullable reference types provide compile-time null safety by distinguishing between nullable and non-nullable reference types.

Enabling Nullable Context

// Project-wide in .csproj
<PropertyGroup>
    <Nullable>enable</Nullable>
</PropertyGroup>

// File-level directive
#nullable enable

public class User
{
    // Non-nullable - must be initialized
    public string Name { get; set; } = string.Empty;

    // Nullable - can be null
    public string? MiddleName { get; set; }

    // Non-nullable - must be set in constructor
    public string Email { get; set; }

    public User(string email)
    {
        Email = email;
    }
}

// Disable for legacy code
#nullable disable

public class LegacyClass
{
    public string Name { get; set; } // Warning suppressed
}

#nullable restore // Return to project default

Non-nullable and Nullable References

#nullable enable

public class PersonService
{
    // ✅ Non-nullable parameter and return type
    public string FormatName(string firstName, string lastName)
    {
        return $"{firstName} {lastName}";
    }

    // ✅ Nullable parameter
    public string FormatNameWithMiddle(string firstName, string? middleName, string lastName)
    {
        if (middleName != null)
        {
            return $"{firstName} {middleName} {lastName}";
        }
        return $"{firstName} {lastName}";
    }

    // ✅ Nullable return type
    public string? FindUserEmail(int userId)
    {
        var user = _repository.Find(userId);
        return user?.Email; // May return null
    }

    // ⚠️ Warning - possible null reference
    public string GetUpperName(string? name)
    {
        // CS8602: Possible null reference
        return name.ToUpper();
    }

    // ✅ Fixed with null check
    public string GetUpperNameSafe(string? name)
    {
        if (name == null)
        {
            throw new ArgumentNullException(nameof(name));
        }
        return name.ToUpper();
    }
}

Nullable Value Types

Value types can be made nullable using Nullable<T> or the ? syntax.

Nullable<T> and T?

public class NullableValueTypes
{
    // Nullable value types
    public int? Age { get; set; }
    public DateTime? BirthDate { get; set; }
    public decimal? Salary { get; set; }
    public bool? IsActive { get; set; }

    // Equivalent to:
    public Nullable<int> AgeVerbose { get; set; }

    public void WorkWithNullables()
    {
        int? value = null;

        // HasValue and Value properties
        if (value.HasValue)
        {
            int actualValue = value.Value;
            Console.WriteLine(actualValue);
        }

        // GetValueOrDefault
        int result1 = value.GetValueOrDefault(); // 0
        int result2 = value.GetValueOrDefault(42); // 42

        // Null coalescing
        int result3 = value ?? 100; // 100
    }

    public int CalculateAge(DateTime? birthDate)
    {
        // ⚠️ Warning - possible null reference
        // return DateTime.Now.Year - birthDate.Value.Year;

        // ✅ Correct with null check
        if (!birthDate.HasValue)
        {
            throw new ArgumentException("Birth date is required", nameof(birthDate));
        }

        return DateTime.Now.Year - birthDate.Value.Year;
    }
}

Nullable Value Type Operations

public class NullableOperations
{
    public void ArithmeticOperations()
    {
        int? a = 5;
        int? b = 10;
        int? c = null;

        // Arithmetic with nullables
        int? sum = a + b; // 15
        int? nullSum = a + c; // null

        // Comparison
        bool? equal = a == b; // false
        bool? nullEqual = a == c; // null (neither true nor false)

        // Lifted operators
        int? result = (a > 0) ? a * 2 : null;
    }

    public decimal? CalculateDiscount(decimal? price, decimal? discountPercent)
    {
        // If either is null, result is null
        return price * (1 - discountPercent / 100);
    }

    public void BooleanLogic()
    {
        bool? a = true;
        bool? b = false;
        bool? c = null;

        // Three-valued logic
        bool? and1 = a & b;  // false
        bool? and2 = a & c;  // null
        bool? and3 = b & c;  // false (false & anything = false)

        bool? or1 = a | b;   // true
        bool? or2 = a | c;   // true (true | anything = true)
        bool? or3 = b | c;   // null
    }
}

Null Safety Annotations

Attributes that provide additional null-safety information to the compiler.

Common Annotations

using System.Diagnostics.CodeAnalysis;

public class AnnotationExamples
{
    // [NotNull] - Parameter won't be null when method returns no
Полный SKILL.md на GitHub

Установить csharp-nullable-types в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Bash
Read
Write
Edit

FAQ

Что делает скилл csharp-nullable-types?

Use when C# nullable reference types, null safety patterns, and migration strategies. Use when ensuring null safety in C# code.

Как установить скилл csharp-nullable-types?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл csharp-nullable-types запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить csharp-nullable-types с