Pattern Matching

Pattern matching is a feature in C# that allows you to check a value against a pattern and execute different code based on the result. It is a more flexible and powerful alternative to the switch statement.

Type Patterns

Type patterns allow you to check if a value is of a specific type.

object value = "Hello, World!";
if (value is string str)
{
    Console.WriteLine($"The value is a string: {str}");
}
else
{
    Console.WriteLine("The value is not a string.");
}

Constant Patterns

Constant patterns allow you to check if a value is equal to a specific constant.

int number = 42;
if (number is 42)
{
    Console.WriteLine("The number is 42.");
}
else
{
    Console.WriteLine("The number is not 42.");
}

Relational Patterns

Relational patterns allow you to check if a value is within a specific range.

int number = 42;
if (number is >= 0 and <= 100)
{
    Console.WriteLine("The number is between 0 and 100.");
}

Logical Patterns

Logical patterns allow you to combine multiple patterns using logical operators.

object value = "Hello, World!";
if (value is string str && str.Length > 5)
{
    Console.WriteLine("The string is longer than 5 characters.");
}
else
{
    Console.WriteLine("The string is not longer than 5 characters.");
}

Property Patterns

Property patterns allow you to check if a value has a specific property.

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Person person = new Person { Name = "John", Age = 30 };
if (person is { Name: "John", Age: 30 })
{
    Console.WriteLine("The person is John and 30 years old.");
}
else
{
    Console.WriteLine("The person is not John and 30 years old.");
}

Positional Patterns

Positional patterns allow you to check if a value matches a specific pattern based on its position in a tuple or array.

(int, string, bool) tuple = (1, "Hello", true);
if (tuple is (1, string str, true))
{
    Console.WriteLine("The tuple matches the pattern.");
}
else
{
    Console.WriteLine("The tuple does not match the pattern.");
}