switch / patterns
C# 8’s switch EXPRESSIONS are the modern default. They return a value, never fall through, and combine with patterns to replace big if chains with declarative dispatch.
Switch expression + property patterns
EXAMPLE
// 1) Basic switch expression
string describe = day switch {
"Sat" or "Sun" => "weekend",
"Mon" or "Tue" or "Wed" or "Thu" or "Fri" => "weekday",
_ => "unknown",
};
// 2) Type patterns + when clauses
string classify(object o) => o switch {
int n when n > 0 => $"positive int {n}",
int => "non-positive int",
string { Length: 0 } => "empty string",
string s => $"string of {s.Length} chars",
null => "null",
_ => "other",
};
// 3) Sealed-type exhaustiveness
public abstract record Shape;
public record Circle(double R) : Shape;
public record Rect(double W, double H) : Shape;
public record Triangle(double Base, double H) : Shape;
double Area(Shape s) => s switch {
Circle c => Math.PI * c.R * c.R,
Rect r => r.W * r.H,
Triangle t => 0.5 * t.Base * t.H,
// compiler warns if you add a new Shape subtype and forget a case
};
// 4) Property patterns — destructure inside a case
public record Order(decimal Total, string Status, Customer Customer);
public record Customer(string Tier);
string fee(Order o) => o switch {
{ Status: "paid", Total: > 1000, Customer.Tier: "gold" } => "VIP: 1%",
{ Status: "paid", Total: > 100 } => "Std: 3%",
{ Status: "refunded" } => "refund",
_ => "std",
};
Why it matters
Property patterns let you peek several levels deep without nesting ifs. Combine with sealed types or records and your business logic stops looking imperative.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
string day = "SAT";
string kind = day switch {
"SAT" or "SUN" => "weekend",
_ => "weekday"
};
Console.WriteLine(kind);
Try it Yourself »
Discussion
Loading…