Logo de Csharp Dotnet

Csharp Dotnet

Comunidade
ericrisco
csharp-dotnet

Use when writing, reviewing, testing, or shipping C# / .NET code — ASP.NET Core APIs (minimal APIs vs controllers), EF Core data access, async correctness, solution layout in .cs/.csproj/.sln. NOT a Java/Spring backend (that is spring-boot), NOT a Node/TypeScript backend (that is nestjs), NOT framework-neutral REST naming (that is api-design).

Visão geral

Publicado porericrisco
Repositóriorsc-harness
Nome da habilidadecsharp-dotnet
Estrelas
239
Forks
24
Arquivos incluídos
5
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 5

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por ericrisco no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Csharp Dotnet no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/ericrisco/rsc-harness/tree/main/skills/csharp-dotnet
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ericrisco/rsc-harness.git /tmp/rsc-harness
mkdir -p .claude/skills
cp -r /tmp/rsc-harness/skills/csharp-dotnet .claude/skills/csharp-dotnet
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Csharp Dotnet em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Csharp Dotnet automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Csharp Dotnet não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Modern C# and .NET services

You write and review C#, ASP.NET Core APIs, and EF Core data access. You own the .NET idioms, the HTTP-contract patterns as expressed in .NET, async correctness, and the .NET-specific quality/security gates. You delegate everything language- agnostic to the right sibling.

Target: .NET 10 (LTS, released 2025-11-11, supported 3 years) with C# 14, EF Core 10, ASP.NET Core 10. .NET 9 / C# 13 is the immediate STS predecessor — still in support but shorter-lived. Features gate on the target framework moniker (TFM): a net10.0 project gets C# 14 by default; a net9.0 project caps at C# 13. When you use a C# 14 feature (field, extension members, null-conditional assignment), say which TFM it requires.

When NOT to use — delegate

SituationRoute to
Java / Spring Boot backendspring-boot
Node / NestJS TypeScript backendnestjs
Language-agnostic threat modeling, OWASP authz/abuse review../secure-coding/SKILL.md
Raw Postgres schema/index/query tuning../postgresdb/SKILL.md
Framework-neutral REST resource taxonomyapi-design
Dockerfile / CI pipeline / deploy target../deployment/SKILL.md
Recording per-project conventions in the workspace wiki../harness/SKILL.md

The .NET expression of an API contract and async correctness live HERE. Resource naming theory lives in api-design; the JVM and Node counterparts are spring-boot and nestjs.

Project & solution layout + dotnet CLI

bash
dotnet new sln -n Shop                         # solution
dotnet new webapi -n Shop.Api                  # minimal API (default in .NET 10)
dotnet new webapi -n Shop.Api --use-controllers # opt into MVC controllers instead
dotnet new xunit -n Shop.Api.Tests             # test project
dotnet sln add Shop.Api Shop.Api.Tests         # wire into the solution
dotnet add Shop.Api package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet ef migrations add Initial -p Shop.Api   # create a migration
dotnet ef database update -p Shop.Api          # apply migrations
dotnet build -warnaserror                      # compile; analyzers + NRT as errors
dotnet test                                    # run tests
dotnet format                                  # apply style; --verify-no-changes in CI
dotnet publish -c Release                       # produce deployable output

Recommended shape:

text
Shop.sln
Directory.Packages.props    # central package management: <PackageVersion> here, no versions in csproj
Directory.Build.props       # shared <Nullable>enable</Nullable>, <TreatWarningsAsErrors>, LangVersion
src/Shop.Api/               # endpoints grouped by feature module (Products/, Orders/)
src/Shop.Domain/            # entities, value objects (no EF/ASP.NET dependency)
tests/Shop.Api.Tests/

Central package management: turn it on with <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> and list versions once in Directory.Packages.props. Why: one source of truth, no version drift across projects.

NRT on for every project — <Nullable>enable</Nullable> in Directory.Build.props. Why: the compiler turns whole classes of NullReferenceException into build-time warnings. Never disable it to silence a warning — fix the nullability.

Modern C# idioms (C# 14 / .NET 10)

DTO as a record, not a class:

csharp
// Bad: mutable class, no value equality, hand-written boilerplate
public class ProductDto { public int Id { get; set; } public string Name { get; set; } }

// Good: immutable record DTO
public record ProductDto(int Id, string Name, decimal Price);

Why: value equality, with expressions, no boilerplate — and never reuse an EF entity as the wire DTO (see anti-patterns).

Pattern matching over if-chains:

csharp
// Bad
if (shape is Circle) { var c = (Circle)shape; return Math.PI * c.R * c.R; }

// Good
return shape switch
{
    Circle c      => Math.PI * c.R * c.R,
    Rectangle r   => r.W * r.H,
    _             => throw new ArgumentOutOfRangeException(nameof(shape)),
};

field keyword — field-backed property without a hand-written backing field (requires C# 14 / net10.0):

csharp
// Bad: explicit backing field just to trim a string
private string _name = "";
public string Name { get => _name; set => _name = value.Trim(); }

// Good (C# 14)
public string Name { get; set => field = value.Trim(); }

Primary constructors, required/init, collection expressions:

csharp
public class OrderService(IOrderRepository repo, ILogger<OrderService> log)  // primary ctor: DI in one line
{
    public required string Region { get; init; }                            // must be set at construction, then immutable
    private static readonly int[] DefaultTiers = [1, 2, 3];                  // collection expression
}

Prefer NRT annotations over defensive null checks: declare string? note when null is valid and let the compiler force callers to handle it, instead of if (x == null) guards scattered everywhere.

Dispose deterministically: using / await using (or using declarations) for anything IDisposable/IAsyncDisposable. Why: leaked connections and handles.

async/await correctness

This is the highest-leverage area to get right. Core rules in body; the full catalog (ConfigureAwait, ValueTask, IAsyncEnumerable, Channels, parallelism, deadlock cases) is in references/async.md — read it before any non-trivial async review.

  • No async void except top-level event handlers. Why: exceptions escape onto the thread pool and crash the process; the caller cannot await or catch it. Use async Task.
  • Never .Result / .Wait() / GetAwaiter().GetResult() on the request path. This is the classic deadlock and the answer to "my endpoint hangs under load":
csharp
// Bad: blocks the thread on an async call -> thread-pool starvation / deadlock under load
public IActionResult Get() => Ok(_svc.LoadAsync().Result);

// Good: await all the way up
public async Task<IActionResult> Get(CancellationToken ct) => Ok(await _svc.LoadAsync(ct));
  • Flow CancellationToken from the endpoint down into every async call — SaveChangesAsync, queries, outbound HTTP. Why: a dropped token means the request keeps running after the client gives up.
  • ValueTask only for hot paths that usually complete synchronously; default to Task. Never await a ValueTask twice.
  • IAsyncEnumerable<T> for streaming results instead of materializing a huge list.

ASP.NET Core APIs

Decision: minimal API for new services; controllers only when you need MVC machinery (model binding conventions, action filters at scale, views). Both can coexist. Why minimal by default: less ceremony, first-class in .NET 10.

Production minimal API shape — route group + DataAnnotations validation (built in for minimal API parameters in .NET 10) + ProblemDetails + OpenAPI 3.1:

csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();                 // OpenAPI 3.1, JSON Schema 2020-12
builder.Services.AddProblemDetails();          // RFC 9457 error bodies
builder.Services.AddDbContext<ShopDb>(o => o.UseNpgsql(builder.Configuration.GetConnectionString("Shop")));

var app = builder.Build();
app.MapOpenApi();                              // serves the OpenAPI document
app.UseExceptionHandler();                     // emits ProblemDetails on unhandled errors

var products = app.MapGroup("/products").WithTags("Products");
products.MapGet("/{id:int}", async (int id, ShopDb db, CancellationToken ct) =>
    await db.Products.AsNoTracking()
        .Where(p => p.Id == id)
        .Select(p => new ProductDto(p.Id, p.Name, p.Price))   // project to DTO, no entity leak
        .FirstOrDefaultAsync(ct) is { } dto
        ? Results.Ok(dto)
        : Results.NotFound());
products.MapPost("/", async (CreateProduct req, ShopDb db, CancellationToken ct) =>
{   // DataAnnotations on CreateProduct are validated automatically in .NET 10
    var entity = new Product { Name = req.Name, Price = req.Price };
    db.Products.Add(entity);
    await db.SaveChangesAsync(ct);
    return Results.Created($"/products/{entity.Id}", new ProductDto(entity.Id, entity.Name, entity.Price));
});
app.Run();

DI lifetimes: Singleton (one for the app), Scoped (one per request — DbContext lives here; it is not thread-safe, so sharing one across requests corrupts change tracking), Transient (new each resolve). Never inject a Scoped service into a Singleton (captive dependency — see anti-patterns). Middleware ordering, endpoint filters, the options pattern, and auth defaults are in references/aspnetcore.md.

EF Core 10

csharp
// Bad: tracking + N+1 — loads orders, then one query per order's customer
var orders = await db.Orders.ToListAsync(ct);
foreach (var o in orders) { var name = o.Customer.Name; /* lazy/round-trip per row */ }

// Good: no-tracking read + single query via projection
var rows = await db.Orders.AsNoTracking()
    .Select(o => new OrderRow(o.Id, o.Customer.Name))   // EF translates to one JOIN
    .ToListAsync(ct);
  • AsNoTracking() on every read-only query — skips change-tracking overhead.
  • Kill N+1 with projection (Select) or Include/ThenInclude; use AsSplitQuery() when an Include cartesian explosion hurts.
  • Migrations: dotnet ef migrations add <Name> then review the generated Up/Down before database update. Never hand-edit applied migrations.
  • EF Core 10 highlights: native json column type, vector type + VECTOR_DISTANCE() for embeddings/RAG, LeftJoin/RightJoin LINQ operators, and named query filters (multiple filters per entity, selectively disabled).

Raw SQL only via parameterized FromSql/ExecuteSql interpolated strings (EF parameterizes the holes). Query patterns, migration workflow, the EF Core 10 features, and raw-SQL safety in full are in references/efcore.md. Schema/index tuning is ../postgresdb/SKILL.md.

.NET security controls

Keep only the .NET-specific controls here; threat modeling and OWASP review go to ../secure-coding/SKILL.md.

  • Parameterized data access — EF LINQ / parameterized FromSql / ADO.NET SqlParameter. Never concatenate user input into SQL. Why: SQL injection.
  • Secrets — dotnet user-secrets in dev, Key Vault / environment in prod. Never in appsettings.json or source.
  • Antiforgery for cookie-auth browser POSTs; Data Protection for cookies/tokens (configure a persisted key ring across instances).
  • Auth defaults — authenticate then authorize via middleware; prefer policy-based authorization; ASP.NET Core 10 is secure-by-default but still verify HTTPS redirection and HSTS in production.

Testing

  • xUnit is the default. Unit-test domain logic with no framework dependency.
  • Integration tests via WebApplicationFactory<Program> — boots the real pipeline in-memory and lets you HttpClient your endpoints.
  • Testcontainers to run a real Postgres in a container for EF integration tests instead of the in-memory provider (which lies about relational behavior).
  • Gate everything with scripts/verify.sh (format + build-warnaserror + test + vuln scan).

Anti-patterns

Anti-patternWhy it bitesDo instead
async void (non-event-handler)Exceptions crash the process; uncatchable by callerasync Task
.Result / .Wait() on request pathDeadlock / thread-pool starvation under loadawait all the way
Scoped service injected into a SingletonCaptive dependency: stale/DbContext reused across requestsInject IServiceScopeFactory, or make the consumer scoped
Reusing an EF entity as the wire DTOOver-posting, serialization cycles, leaked columnsSeparate record DTO + mapping
Tracking queries on read-only readsWasted memory/CPU on change trackingAsNoTracking()
Lazy navigation in a loopN+1 round-tripsProjection or Include
Missing CancellationTokenWork continues after client disconnectsFlow the token to all I/O
catch (Exception) { } swallowHides failures; corrupt state continuesHandle specifically or let UseExceptionHandler map it
<Nullable>disable</Nullable> to mute a warningRe-opens the NRE class of bugsKeep NRT on; fix the nullability

Project grounding

Record per-project conventions (target TFM, package manager, lint rules, deploy target) in the workspace wiki via ../harness/SKILL.md, not inline assumptions. Before calling a C# change done, run scripts/verify.sh from the solution/project root.

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Csharp Dotnet faz?

Use when writing, reviewing, testing, or shipping C# / .NET code — ASP.NET Core APIs (minimal APIs vs controllers), EF Core data access, async correctness, solution layout in .cs/.csproj/.sln. NOT a Java/Spring backend (that is spring-boot), NOT a Node/TypeScript backend (that is nestjs), NOT framework-neutral REST naming (that is api-design).

Por que usar Csharp Dotnet no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Csharp Dotnet é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Csharp Dotnet no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/ericrisco/rsc-harness/tree/main/skills/csharp-dotnet. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Csharp Dotnet?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Csharp Dotnet?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Csharp Dotnet com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Csharp Dotnet é gratuita?

Sim. A habilidade é publicada no GitHub por ericrisco sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇