Command Palette

Search for a command to run...

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

csharp-advanced-patterns

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

Master advanced C# patterns including records, pattern matching, async/await, LINQ, and performance optimization for .NET 10. Use when: (1) implementing…

thapaliyabikendraот thapaliyabikendra★ 25 звёзд на GitHub11 установок в других каталогах

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

C# Advanced Patterns

Advanced C# language patterns and .NET 10 features for elegant, performant code.

When to Use

  • Implementing complex business logic with pattern matching
  • Optimizing async/await usage
  • Writing performant code with Span/Memory
  • Refactoring legacy code to modern C#
  • Creating immutable DTOs with records

Modern C# Features (.NET 10)

Records for DTOs

// Immutable DTO with required properties
public record CreatePatientDto
{
    public required string FirstName { get; init; }
    public required string LastName { get; init; }
    public required string Email { get; init; }
    public DateTime DateOfBirth { get; init; }
}

// Positional record with deconstruction
public record PatientDto(Guid Id, string FullName, string Email);

// Usage
var (id, name, email) = patient;

Pattern Matching

// Switch expression for status handling
public string GetStatusMessage(AppointmentStatus status) => status switch
{
    AppointmentStatus.Scheduled => "Your appointment is confirmed",
    AppointmentStatus.Completed => "Thank you for visiting",
    AppointmentStatus.Cancelled => "Your appointment was cancelled",
    AppointmentStatus.NoShow => "You missed your appointment",
    _ => throw new ArgumentOutOfRangeException(nameof(status))
};

// Property pattern matching
public decimal CalculateDiscount(Patient patient) => patient switch
{
    { Age: > 65 } => 0.20m,
    { IsVeteran: true } => 0.15m,
    { Visits: > 10 } => 0.10m,
    _ => 0m
};

// List patterns (.NET 7+)
public string DescribeList(int[] numbers) => numbers switch
{
    [] => "Empty",
    [var single] => $"Single: {single}",
    [var first, .., var last] => $"First: {first}, Last: {last}",
};

Primary Constructors

// Class with primary constructor
public class PatientService(
    IRepository<Patient, Guid> repository,
    ILogger<PatientService> logger)
{
    public async Task<Patient> GetAsync(Guid id)
    {
        logger.LogInformation("Getting patient {Id}", id);
        return await repository.GetAsync(id);
    }
}

Collection Expressions

// Modern collection initialization
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];
Span<int> span = [1, 2, 3];

// Spread operator
int[] combined = [..numbers, 6, 7, 8];

Async/Await Patterns

Proper Async with Cancellation

public async Task<PatientDto> GetPatientAsync(
    Guid id,
    CancellationToken cancellationToken = default)
{
    var patient = await _repository
        .GetAsync(id, cancellationToken);

    return ObjectMapper.Map<Patient, PatientDto>(patient);
}

Parallel Processing with SemaphoreSlim

public async Task ProcessPatientsAsync(
    IEnumerable<Guid> patientIds,
    CancellationToken ct)
{
    var semaphore = new SemaphoreSlim(10); // Max 10 concurrent
    var tasks = patientIds.Select(async id =>
    {
        await semaphore.WaitAsync(ct);
        try
        {
            await ProcessPatientAsync(id, ct);
        }
        finally
        {
            semaphore.Release();
        }
    });

    await Task.WhenAll(tasks);
}

ValueTask for Hot Paths

// Use ValueTask when result is often synchronous
public ValueTask<Patient?> GetCachedPatientAsync(Guid id)
{
    if (_cache.TryGetValue(id, out var patient))
        return ValueTask.FromResult<Patient?>(patient);

    return new ValueTask<Patient?>(LoadPatientAsync(id));
}

Channel for Producer/Consumer

public class PatientProcessor
{
    private readonly Channel<Patient> _channel =
        Channel.CreateBounded<Patient>(100);

    public async Task ProduceAsync(Patient patient, CancellationToken ct)
    {
        await _channel.Writer.WriteAsync(patient, ct);
    }

    public async Task ConsumeAsync(CancellationToken ct)
    {
        await foreach (var patient in _channel.Reader.ReadAllAsync(ct))
        {
            await ProcessAsync(patient);
        }
    }
}

Result Pattern

public readonly record struct Result<T>
{
    public T? Value { get; }
    public string? Error { get; }
    public bool IsSuccess => Error is null;

    private Result(T value) => Value = value;
    private Result(string error) => Error = error;

    public static Result<T> Success(T value) => new(value);
    public static Result<T> Failure(string error) => new(error);

    public TResult Match<TResult>(
        Func<T, TResult> onSuccess,
        Func<string, TResult> onFailure)
        => IsSuccess ? onSuccess(Value!) : onFailure(Error!);
}

// Usage
public Result<Patient> CreatePatient(CreatePatientDto dto)
{
    if (string.IsNullOrEmpty(dto.Email))
        return Result<Patient>.Failure("Email is required");

    var patient = new Patient(dto.FirstName, dto.LastName, dto.Email);
    return Result<Patient>.Success(patient);
}

Extension Methods

public static class PatientExtensions
{
    public static string Ge
Полный SKILL.md на GitHub

Установить csharp-advanced-patterns в Claude Code и Claude Desktop

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

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

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

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

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

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл csharp-advanced-patterns?

Master advanced C# patterns including records, pattern matching, async/await, LINQ, and performance optimization for .NET 10. Use when: (1) implementing complex C# patterns, (2) optimizing performance, (3) refactoring legacy code, (4) writing modern idiomatic C#.

Как установить скилл csharp-advanced-patterns?

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

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

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

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

Сравнить csharp-advanced-patterns с