MCPInstall

dotnet-csharp-code-smells

Reviewing C for logic issues. Anti-patterns, common pitfalls, async misuse, DI mistakes.

Installs
169
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-code-smells
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads dotnet-csharp-code-smells automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

dotnet-csharp-code-smells

Proactive code-smell and anti-pattern detection for C# code. This skill triggers during all workflow modes -- planning, implementation, and review. Each entry identifies the smell, explains why it is harmful, provides the correct fix, and references the relevant CA rule or cross-reference.

Cross-references: [skill:dotnet-csharp-async-patterns] for async gotchas, [skill:dotnet-csharp-coding-standards] for naming and style, [skill:dotnet-csharp-dependency-injection] for DI lifetime misuse, [skill:dotnet-csharp-nullable-reference-types] for NRT annotation mistakes.

Out of Scope: LLM-specific generation mistakes (wrong NuGet packages, bad project structure, MSBuild errors) are covered by [skill:dotnet-agent-gotchas]. This skill covers general .NET code smells that any developer -- human or AI -- should avoid.


1. Resource Management (IDisposable Misuse)

SmellWhy HarmfulFixRule
Missing using on disposable localsLeaks unmanaged handles (sockets, files, DB connections)Wrap in using declaration or using blockCA2000
Undisposed IDisposable fieldsClass holds disposable resource but never disposes itImplement IDisposable; dispose fields in Dispose()CA2213
Wrong Dispose pattern (no finalizer guard)Double-dispose or missed cleanup on GC finalizationFollow canonical Dispose(bool) pattern; call GC.SuppressFinalize(this)CA1816
Disposable created in one method, stored in fieldOwnership unclear; easy to forget disposalDocument ownership; make the containing class IDisposableCA2000
using on non-owned resourcePremature disposal of shared resource (e.g., injected HttpClient)Only dispose resources you create; let DI manage injected services--

See details.md for code examples of each pattern.


2. Warning Suppression Hacks

SmellWhy HarmfulFixRule
Invoking event with null to suppress CS0067Creates misleading runtime behavior; masks real bugsUse #pragma warning disable CS0067 or explicit event accessors { add {} remove {} }CS0067
Dummy variable assignments to suppress CS0219Dead code that confuses readersUse _ = expression; discard or #pragma warning disableCS0219
Blanket #pragma warning disable without restoreSuppresses ALL warnings for rest of fileAlways pair with #pragma warning restore; suppress specific codes only--
[SuppressMessage] without justificationFuture maintainers cannot evaluate if suppression is still validAlways include Justification = "reason"CA1303

See details.md for the CS0067 motivating example (bad pattern to correct fix).


3. LINQ Anti-Patterns

SmellWhy HarmfulFixRule
Premature .ToList() mid-chainForces full materialization; wastes memoryKeep chain lazy; materialize only at the endCA1851
Multiple enumeration of IEnumerable<T>Re-executes query or DB call on each enumerationMaterialize once with .ToList() then reuseCA1851
Client-side evaluation in EF CoreLoads entire table into memory; silent perf bombRewrite query as translatable LINQ or use AsAsyncEnumerable() with explicit intent--
.Count() > 0 instead of .Any()Enumerates entire collection instead of short-circuitingUse .Any() for existence checksCA1827
Nested foreach instead of .Join() or .GroupJoin()O(n*m) when O(n+m) is possibleUse LINQ join operations or Dictionary lookup--
.Where().First() instead of .First(predicate)Creates unnecessary intermediate iteratorPass predicate directly to .First() or .FirstOrDefault()CA1826

4. Event Handling Leaks

SmellWhy HarmfulFixRule
Not unsubscribing from eventsMemory leak: publisher holds reference to subscriberUnsubscribe in Dispose() or use weak event pattern--
Raising events in constructorSubscribers may not be attached yet; derived class not fully constructedRaise events only from fully initialized instancesCA2214
async void event handler (misused)async void is the only valid signature for event handlers, but exceptions are unobservableWrap body in try/catch; log and handle exceptions explicitly--
Event handler not checking for nullNullReferenceException when no subscribersUse event?.Invoke() null-conditional pattern--
Static event without cleanupRooted references prevent GC for application lifetimePrefer instance events or use WeakEventManager--

Cross-reference: [skill:dotnet-csharp-async-patterns] covers async void fire-and-forget patterns in depth.


5. Design Smells

SmellThresholdWhy HarmfulFix
God class>500 linesToo many responsibilities; hard to test and maintainExtract cohesive classes using SRP
Long method>30 linesHard to understand, test, and reviewExtract helper methods with descriptive names
Long parameter list>5 parametersIndicates missing abstractionIntroduce parameter object or builder
Feature envyMethod uses another class's data more than its ownMisplaced responsibility; tight couplingMove method to the class it envies
Primitive obsessionDomain concepts represented as raw string/intNo type safety; validation scatteredIntroduce value objects or strongly-typed IDs
Deep nesting>3 levels of indentationHard to follow control flowUse guard clauses (early return) and extract methods

6. Exception Handling Gaps

SmellWhy HarmfulFixRule
Empty catch blockSilently swallows errors; masks bugsAt minimum, log the exception; prefer letting it propagateCA1031
Catching base ExceptionCatches OutOfMemoryException, StackOverflowException, etc.Catch specific exception typesCA1031
Log-and-swallow (catch { log; })Caller never learns operation failedRe-throw after logging, or return error result--
Throwing in finallyMasks original exception with the new oneUse try/catch inside finally; never throw from finally--
throw ex; instead of throw;Resets stack trace; hides original failure locationUse bare throw; to preserve stack traceCA2200
Not including inner exceptionLoses causal chain when wrapping exceptionsPass original as innerException parameter--

Cross-reference: [skill:dotnet-csharp-async-patterns] covers exception handling in fire-and-forget and async void scenarios.


Quick Reference: CA Rules

RuleDescription
CA1031Do not catch general exception types
CA1816Call GC.SuppressFinalize correctly
CA1826Do not use Enumerable methods on indexable collections
CA1827Do not use Count()/LongCount() when Any() can be used
CA1851Possible multiple enumerations of IEnumerable collection
CA2000Dispose objects before losing scope
CA2200Rethrow to preserve stack details
CA2213Disposable fields should be disposed
CA2214Do not call overridable methods in constructors

Enable these via <AnalysisLevel>latest-all</AnalysisLevel> in your project. See [skill:dotnet-csharp-coding-standards] for analyzer configuration.


References

FAQ

What does the dotnet-csharp-code-smells skill do?

Reviewing C for logic issues. Anti-patterns, common pitfalls, async misuse, DI mistakes.

How do I install dotnet-csharp-code-smells?

Run npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-code-smells in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/dotnet-csharp-code-smells/ (personal) or .claude/skills/dotnet-csharp-code-smells/ (project).

Which AI agents can use dotnet-csharp-code-smells?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is dotnet-csharp-code-smells safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains dotnet-csharp-code-smells?

It is published by wshaddix in wshaddix/dotnet-skills. It has 169 recorded installs.

More from wshaddix/dotnet-skills

View all →

dotnet-xunit

wshaddix/dotnet-skills

Writing xUnit tests. v3 Fact/Theory, fixtures, parallelism, IAsyncLifetime, v2 compatibility.

Backend & APIs613 installs

dotnet-testing-strategy

wshaddix/dotnet-skills

Deciding how to test .NET code. Unit vs integration vs E2E decision tree, test doubles.

Testing & QA610 installs

modern-csharp-coding-standards

wshaddix/dotnet-skills

Write modern, high-performance C code using records, pattern matching, value objects, async/await, Span /Memory , and best-practice API design patterns. Emphasizes functional-style programming with C 12+ features. Use when writing new C code or refactoring existing code, designing public APIs for libraries or services, optimizing performance-critical code paths, or building async/await-heavy applications.

csharp-wolverinefx

wshaddix/dotnet-skills

Build .NET applications with WolverineFX for messaging, HTTP services, and event sourcing. Use when implementing command handlers, message handlers, HTTP endpoints with WolverineFx.HTTP, transactional outbox patterns, event sourcing with Marten, CQRS architectures, cascading messages, batch message processing, or configuring transports like RabbitMQ, Azure Service Bus, or Amazon SQS.

Backend & APIs570 installs

testcontainers

wshaddix/dotnet-skills

Patterns for using Testcontainers in .NET integration tests to spin up real dependencies like databases and message queues. Use when writing integration tests that require real databases, testing with message brokers like RabbitMQ or Kafka, or isolating test dependencies with Docker containers.

Testing & QA565 installs

Dependency injection patterns and best practices using Microsoft.Extensions.DependencyInjection for .NET applications. Use when configuring DI containers in .NET, choosing between service lifetimes (Singleton, Scoped, Transient), or implementing decorator patterns and service interception.

Security549 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs