CHASH Tutorial



C# PATTERN MATCHING


Pattern Matching in C#

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.

1. Type Pattern

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");
}
  

2. Constant Pattern

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;
}
  

3. Property Pattern

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.");
}
  

4. Tuple Pattern

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

  • Type Pattern: Checks object type and extracts variable.
  • Constant Pattern: Matches specific constant values.
  • Property Pattern: Matches objects by their properties.
  • Tuple Pattern: Matches tuples or multiple values at once.

💡 Quick Tip:

Pattern matching simplifies your code by combining type checking and conditional logic into one elegant statement.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review