Pattern matching in switch helps you check a value against different shapes or types easily. It makes your code cleaner and easier to read.
Pattern matching in switch in C Sharp (C#)
switch (variable) { case TypeName variableName: // code when variable is TypeName break; case TypeName { Property: value } variableName: // code when variable matches pattern with property break; case int number when number > 0: // code when variable is int and greater than 0 break; case null: // code when variable is null break; default: // code for all other cases break; }
You can match types, properties, and add extra conditions with when.
Use default to catch all unmatched cases.
value and prints a message accordingly.object value = 42; switch (value) { case int number: Console.WriteLine($"It's an integer: {number}"); break; case string text: Console.WriteLine($"It's a string: {text}"); break; default: Console.WriteLine("Unknown type"); break; }
object value = "hello"; switch (value) { case string { Length: > 3 } longText: Console.WriteLine($"Long string: {longText}"); break; case string shortText: Console.WriteLine($"Short string: {shortText}"); break; default: Console.WriteLine("Not a string"); break; }
object value = null; switch (value) { case null: Console.WriteLine("Value is null"); break; default: Console.WriteLine("Value is not null"); break; }
This program shows how to use pattern matching in a switch to handle different types and conditions. It prints the items before and after applying the switch with patterns.
using System; class Program { static void Main() { object[] items = { 10, "hello", 3.14, null, "hi" }; Console.WriteLine("Before switch pattern matching:"); foreach (var item in items) { Console.WriteLine(item ?? "null"); } Console.WriteLine("\nAfter switch pattern matching:"); foreach (var item in items) { switch (item) { case int number when number > 5: Console.WriteLine($"Integer greater than 5: {number}"); break; case int number: Console.WriteLine($"Integer 5 or less: {number}"); break; case string { Length: > 3 } longText: Console.WriteLine($"Long string: {longText}"); break; case string shortText: Console.WriteLine($"Short string: {shortText}"); break; case null: Console.WriteLine("Null value found"); break; default: Console.WriteLine($"Other type: {item}"); break; } } } }
Time complexity depends on the number of cases but is generally efficient for small sets.
Space complexity is minimal as no extra storage is needed beyond the switch.
Common mistake: forgetting to handle null values can cause runtime errors.
Use pattern matching in switch when you want clear, readable code for multiple type or condition checks instead of many if-else statements.
Pattern matching in switch lets you check types and conditions clearly.
You can match properties and add extra checks with when.
It helps write cleaner and easier-to-read code than many if-else statements.