C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 31

What is pattern matching in C#?

Answer:

Pattern matching in C# is a feature that allows you to test the shape or structure of data and extract information from it in a concise and readable manner. Introduced in C# 7.0 and enhanced in subsequent versions, pattern matching provides a powerful way to work with different types and structures, improving code readability and maintainability.

Key Concepts of Pattern Matching

  1. Type Patterns:

    • Checks if an expression is of a specified type and casts it to that type if the match is successful.
  2. Constant Patterns:

    • Compares an expression to a constant value.
  3. Property Patterns:

    • Checks if an object's properties match specified patterns.
  4. Positional Patterns:

    • Checks if the elements of a tuple or deconstructed value match specified patterns.
  5. Switch Expressions:

    • Provides a concise syntax for switch statements, allowing for pattern matching within the switch.

Basic Syntax and Examples

Type Patterns

Type patterns check if an expression is of a specified type and, if so, cast it to that type.

Example:

public void PrintObject(object obj)
{
    if (obj is string s)
    {
        Console.WriteLine($"String of length {s.Length}");
    }
    else if (obj is int i)
    {
        Console.WriteLine($"Integer with value {i}");
    }
    else
    {
        Console.WriteLine("Unknown type");
    }
}

Constant Patterns

Constant patterns compare an expression to a constant value.

Example:

public string GetDayType(int dayOfWeek)
{
    return dayOfWeek switch
    {
        0 => "Sunday",
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 => "Saturday",
        _ => "Invalid day"
    };
}

Property Patterns

Property patterns check if an object's properties match specified patterns.

Example:

public string GetPersonDescription(Person person)
{
    return person switch
    {
        { Age: < 18 } => "Child",
        { Age: >= 18, Age: < 65 } => "Adult",
        { Age: >= 65 } => "Senior",
        _ => "Unknown"
    };
}

Positional Patterns

Positional patterns check if the elements of a tuple or deconstructed value match specified patterns.

Example:

public void Deconstruct(Point point)
{
    (int x, int y) = point;
    Console.WriteLine($"Point coordinates: ({x}, {y})");
}

public string GetQuadrant(Point point)
{
    return point switch
    {
        (0, 0) => "Origin",
        var (x, y) when x > 0 && y > 0 => "Quadrant I",
        var (x, y) when x < 0 && y > 0 => "Quadrant II",
        var (x, y) when x < 0 && y < 0 => "Quadrant III",
        var (x, y) when x > 0 && y < 0 => "Quadrant IV",
        _ => "On an axis"
    };
}

Switch Expressions

Switch expressions provide a more concise and expressive syntax for switch statements, supporting pattern matching directly within the switch.

Example:

public string DescribeShape(IShape shape)
{
    return shape switch
    {
        Circle c => $"Circle with radius {c.Radius}",
        Rectangle r => $"Rectangle with width {r.Width} and height {r.Height}",
        _ => "Unknown shape"
    };
}

Advanced Features

Combining Patterns

Patterns can be combined using logical operators like and, or, and not.

Example:

public string DescribeNumber(int number)
{
    return number switch
    {
        > 0 and < 10 => "Single-digit positive number",
        >= 10 and < 100 => "Double-digit positive number",
        _ => "Other number"
    };
}

Recursive Patterns

Recursive patterns allow patterns to be nested within each other, enabling complex matching scenarios.

Example:

public string DescribePerson(Person person)
{
    return person switch
    {
        { Name: "John", Address: { City: "New York" } } => "John from New York",
        { Name: "Jane", Address: { City: "Los Angeles" } } => "Jane from Los Angeles",
        _ => "Someone else"
    };
}

Benefits of Pattern Matching

  1. Readability:

    • Pattern matching makes the code more readable and expressive by clearly showing the intent of the matching logic.
  2. Conciseness:

    • It reduces boilerplate code and provides a more concise way to handle different cases.
  3. Type Safety:

    • Pattern matching ensures type safety by allowing the compiler to check the patterns at compile time.
  4. Flexibility:

    • It provides a flexible way to decompose and analyze data structures, making it easier to work with complex data.

Summary

Pattern matching in C# is a powerful feature that allows you to test the shape or structure of data and extract information from it in a concise and readable manner. It supports various patterns, including type patterns, constant patterns, property patterns, and positional patterns, and enhances switch statements with switch expressions. By using pattern matching, you can write more expressive, concise, and type-safe code.

Recent job openings