| name | csharp |
| description | C# and .NET 8+ coding conventions, naming standards, idiomatic patterns, CLI commands, dependency management, testing with xUnit, and XML documentation. Use when writing, reviewing, or refactoring C# code. |
C# Coding Guidelines
Code Style and Naming Conventions
- Classes, Records, Structs:
PascalCase
- Interfaces:
IPascalCase (prefixed with 'I')
- Methods, Properties, Events:
PascalCase
- Local Variables and Parameters:
camelCase
- Private/Protected Fields:
_camelCase (leading underscore)
- Constants / Readonly variables:
PascalCase (avoid SCREAMING_SNAKE_CASE)
- Braces: Allman style (opening and closing braces on their own lines)
- Implicit Typing (
var): Use var when type is obvious from the assignment. Use explicit type for primitives or when unclear.
CLI Commands (.NET 8+)
dotnet build
dotnet format
dotnet test
dotnet run
dotnet add package <PackageName>
dotnet add reference <ProjectPath>
Dependency Management
- Rely on built-in Dependency Injection (
Microsoft.Extensions.DependencyInjection).
- Register services via
AddSingleton, AddScoped, or AddTransient.
HttpClient should be injected via IHttpClientFactory or registered as a singleton to avoid socket exhaustion.
Idiomatic C# Patterns
public record CustomerDto(string Name, string Email);
namespace MyProject.Services;
global using System.Linq;
global using Microsoft.Extensions.Logging;
if (obj is Customer { IsPremium: true } premiumCustomer)
{
}
var discount = customer switch
{
{ IsPremium: true } => 0.2m,
_ => 0m
};
var activeUsers = users.Where(u => u.IsActive).ToList();
public async Task<string> GetDataAsync(CancellationToken cancellationToken)
{
return await _httpClient.GetStringAsync(url, cancellationToken);
}
Anti-patterns to Avoid
- ❌ Primitive Obsession: Prefer domain specific wrappers or records over raw strings/ints (e.g.,
EmailAddress record vs string).
- ❌ Catching Exception blindly: Never use
catch (Exception ex) without logging or throw;. Never use throw ex; as it destroys stack trace.
- ❌ Using blocks for HttpClient: Do not wrap
HttpClient in using. Register it properly or use IHttpClientFactory.
- ❌ Magic numbers/strings: Use named
const variables or enums.
- ❌ Classic Singleton Pattern: Don't write manual
public static MyService Instance. Use DI.
Testing Frameworks
- Primarily use xUnit (
xunit.v3 for modern testing).
[Fact] for parameterless tests.
[Theory] and [InlineData] for parameterized tests.
XML Documentation Comments
Use triple-slash /// XML comments for public APIs. This powers tools like Swagger/OpenAPI.
public decimal CalculateTotal(decimal orderAmount, decimal taxRate)
Quick Checklist