Types and collections
| Pattern | Purpose | Boundary |
|---|---|---|
decimal amount = 12.50m; |
Represents a decimal amount | Define the required rounding rule |
int? count = null; |
Separates absence from a recorded integer | Zero can be a valid value |
map.TryGetValue(key, out var value) |
Separates a missing key from its default value | Pick the key comparer deliberately |
items.ToArray() |
Copies elements into a new array | Reference elements can still share objects |
new HashSet<string>(StringComparer.OrdinalIgnoreCase) |
Uses ordinal case-insensitive identity | It doesn’t preserve a required display order |
LINQ and order
var result = rows
.Where(row => row.Active)
.OrderByDescending(row => row.Total)
.ThenBy(row => row.Id)
.Select(row => row.Id)
.ToArray();
Use ThenBy for a secondary key. Another OrderBy replaces the earlier primary ordering. Decide what empty input means before using First or Average. Materialize once when several consumers need the same snapshot; check provider translation before moving work out of the database.
Async and cancellation
public static async Task<int> ReadAsync(
Func<CancellationToken, Task<int>> read,
CancellationToken token)
{
token.ThrowIfCancellationRequested();
return await read(token);
}
This passes cancellation into the operation. The operation must observe the token too. Task.WhenAll coordinates completion; it doesn’t limit the number of tasks you start. Use a deliberate concurrency limit when the downstream service needs one.
Memory and disposal
int[] values = { 2, 4, 6 };
Span<int> middle = values.AsSpan(1, 1);
middle[0] = 9;
The array now contains 2, 9, 6. The span is a view. A read-only view prevents writes through that view but doesn’t make the underlying array immutable.
using var stream = new MemoryStream(); disposes the acquired stream at the end of the enclosing scope, including early exits. Dispose resources you own. The GC’s reachability rules don’t provide a deterministic close time.
Use the C# course for checked tasks, the exercises for small contracts and the .NET interview questions for explanations of the failure cases.