Pattern matching is the most powerful logic evolution in C# history. It allows you to test variables against "shapes" and extract data simultaneously. It has almost entirely replaced the old, bulky switch statements in modern enterprise codebases.
Instead of the verbose case: and break; syntax, we use a concise, functional-style arrow syntax.
int categoryId = 1;
string categoryName = categoryId switch
{
1 => "Electronics",
2 => "Clothing",
3 => "Books",
_ => "Other" // The '_' is the default "discard" pattern
};
You can now perform mathematical and logical checks directly inside a switch statement!
var temp = 25;
string status = temp switch
{
< 0 => "Freezing",
>= 0 and <= 20 => "Cold",
> 20 and < 35 => "Warm",
>= 35 => "Hot",
_ => "Unknown"
};
You can "reach inside" an object to check its internal property values without writing nested if statements.
if (user is { IsAdmin: true, IsActive: true })
{
Console.WriteLine("Access Granted!");
}
Q: "What is the 'is' keyword pattern, and how does it make our code safer during type-casting?"
Architect Answer: "The 'is' pattern combines two steps into one: Type Checking and Variable Assignment. In legacy C#, you had to check if an object was a string, and then cast it: `if (obj is string) { var s = (string)obj; ... }`. This is risky. With Pattern Matching, we write: `if (obj is string message)`. If the check succeeds, C# automatically creates the `message` variable, casts it, and makes it available inside the scope. This eliminates the 'Double-Cast' performance penalty and prevents `InvalidCastException` crashes entirely."