Tips & tricks
Small idioms with a big payoff.
Switch expressions and pattern matching
Property, positional and relational patterns replace long if/else chains.
string Describe(object shape) => shape switch
{
Circle { Radius: > 10 } => "large circle",
Circle c => quot;circle r={c.Radius}",
Rectangle(var w, var h) when w == h => "square",
null => "nothing",
_ => "unknown shape",
};Records with with-expressions
Immutable data types with value equality in one line.
public record Money(decimal Amount, string Currency);
var price = new Money(10m, "CAD");
var discounted = price with { Amount = 8m }; // non-destructive copy
Console.WriteLine(price == new Money(10m, "CAD")); // True: value equalityusing declarations
No extra braces; disposal happens at the end of the enclosing scope.
await using var conn = new SqlConnection(cs); // disposed at end of scope
var users = await conn.QueryAsync<User>("select * from users"); // e.g. DapperSaved in this browser only. Part of Clean code foundations (0/5).