Pattern matching allows you to check an object against a pattern. It is very useful with switch
statements, if
statements, and is
expressions to write cleaner and more readable code.
Use is
to check if an object is of a certain type and declare a variable if it matches.
object obj = 123;
if (obj is int number)
{
Console.WriteLine($"Integer value: {number}");
}
else
{
Console.WriteLine("Not an integer");
}
Match a value with a constant inside a switch
or if
statement.
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Other day");
break;
}
Match objects based on their properties.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person p = new Person { Name = "Alice", Age = 25 };
if (p is { Age: > 18 })
{
Console.WriteLine($"{p.Name} is an adult.");
}
Match multiple values using tuples.
int x = 1;
int y = 2;
switch ((x, y))
{
case (0, 0):
Console.WriteLine("Origin");
break;
case (1, _):
Console.WriteLine("X is 1");
break;
default:
Console.WriteLine("Other point");
break;
}
Summary
💡 Quick Tip:
Pattern matching simplifies your code by combining type checking and conditional logic into one elegant statement.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!