csharp
C# 12 language features including records, pattern matching, nullable reference types, LINQ, async/await, and modern language patterns. USE WHEN: user mentions "C#", "C# records", "pattern matching", "LINQ", "async/await", "nullable reference types", "C# generics", "C# language features" DO NOT USE FOR: TypeScript - use `typescript`, Java - use Java skills, F# or VB.NET specific features
What this skill does
# C# 12 - Quick Reference
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `csharp` for comprehensive documentation.
## Records
```csharp
// Positional record (immutable)
public record UserDto(int Id, string Name, string Email);
// Record with additional members
public record OrderDto(int Id, decimal Total)
{
public string FormattedTotal => Total.ToString("C");
}
// Record struct (value type, C# 10)
public readonly record struct Point(double X, double Y);
// With-expression (non-destructive mutation)
var updated = user with { Name = "New Name" };
```
## Pattern Matching (C# 12)
```csharp
// Switch expression
string GetDiscount(Customer customer) => customer switch
{
{ Type: CustomerType.Premium, YearsActive: > 5 } => "30%",
{ Type: CustomerType.Premium } => "20%",
{ Type: CustomerType.Regular, YearsActive: > 3 } => "10%",
_ => "0%",
};
// List patterns (C# 11)
var result = numbers switch
{
[1, 2, 3] => "exact match",
[1, .., 3] => "starts with 1, ends with 3",
[_, > 5, ..] => "second element > 5",
[] => "empty",
_ => "other",
};
// Type pattern with when
if (shape is Circle { Radius: > 10 } circle)
{
Console.WriteLine($"Large circle: {circle.Radius}");
}
```
## Nullable Reference Types
```csharp
// Enable in .csproj: <Nullable>enable</Nullable>
public class UserService
{
// Nullable return type
public User? FindById(int id) => _users.FirstOrDefault(u => u.Id == id);
// Non-nullable parameter
public void Update(User user)
{
ArgumentNullException.ThrowIfNull(user);
// user is guaranteed non-null here
}
// Null-conditional and coalescing
public string GetDisplayName(User? user)
=> user?.Name ?? "Unknown";
// Required members (C# 11)
public required string Name { get; init; }
}
```
## Async/Await Patterns
```csharp
// Basic async method
public async Task<User> GetUserAsync(int id)
{
var user = await _repository.FindAsync(id);
return user ?? throw new NotFoundException($"User {id} not found");
}
// Parallel async
public async Task<(User[], Order[])> GetDashboardDataAsync(int userId)
{
var usersTask = _userService.GetAllAsync();
var ordersTask = _orderService.GetByUserAsync(userId);
await Task.WhenAll(usersTask, ordersTask);
return (usersTask.Result, ordersTask.Result);
}
// IAsyncEnumerable
public async IAsyncEnumerable<User> GetUsersStreamAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var user in _context.Users.AsAsyncEnumerable().WithCancellation(ct))
{
yield return user;
}
}
// ValueTask for hot paths
public ValueTask<User?> GetCachedUserAsync(int id)
{
if (_cache.TryGetValue(id, out var user))
return ValueTask.FromResult<User?>(user);
return new ValueTask<User?>(LoadUserAsync(id));
}
```
## LINQ
```csharp
// Method syntax (preferred)
var result = users
.Where(u => u.IsActive)
.OrderBy(u => u.Name)
.Select(u => new { u.Name, u.Email })
.ToList();
// GroupBy
var grouped = orders
.GroupBy(o => o.Status)
.Select(g => new { Status = g.Key, Count = g.Count(), Total = g.Sum(o => o.Amount) });
// Aggregate
var summary = orders.Aggregate(
new { Count = 0, Total = 0m },
(acc, order) => new { Count = acc.Count + 1, Total = acc.Total + order.Amount });
// Chunk (C# 12 / .NET 8)
var batches = users.Chunk(100); // IEnumerable<User[]>
```
## Primary Constructors (C# 12)
```csharp
// Class primary constructor
public class UserService(IUserRepository repository, ILogger<UserService> logger)
{
public async Task<User> GetByIdAsync(int id)
{
logger.LogInformation("Getting user {Id}", id);
return await repository.GetByIdAsync(id)
?? throw new NotFoundException($"User {id} not found");
}
}
// Record primary constructor (already existed)
public record UserDto(int Id, string Name, string Email);
```
## Collection Expressions (C# 12)
```csharp
// Array
int[] numbers = [1, 2, 3, 4, 5];
// List
List<string> names = ["Alice", "Bob", "Charlie"];
// Spread
int[] first = [1, 2, 3];
int[] second = [4, 5, 6];
int[] combined = [..first, ..second]; // [1, 2, 3, 4, 5, 6]
```
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| `.Result` / `.Wait()` | Deadlocks | Use `async/await` |
| `async void` | Exceptions lost | Use `async Task` |
| Mutable DTOs | Unexpected mutations | Use `record` types |
| No null checking | NullReferenceException | Enable nullable references |
| String concatenation in loops | Memory pressure | Use `StringBuilder` |
## Quick Troubleshooting
| Issue | Likely Cause | Solution |
|-------|--------------|----------|
| Nullable warning | Missing null check | Add `?`, `??`, or null guard |
| Deadlock | `.Result` in async context | Use `await` |
| LINQ multiple enumeration | Iterating IEnumerable twice | Call `.ToList()` first |
| Record equality fails | Reference type property | Override `Equals` or use value types |
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.