Property Pattern in c#

Property Pattern in c#


Property Pattern in C#

Property patterns in C# are part of the broader pattern matching capabilities introduced in recent versions of the language. They allow developers to match expressions based on properties of objects in a concise and readable manner. This article covers various aspects of pattern matching, including the property pattern, with practical examples to demonstrate their use.

Property Pattern in C# with Example

The property pattern enables matching based on the properties of an object. It is especially useful in switch expressions. Here’s an example using a Car class:

 

public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
}

public string GetCarInfo(Car car) =>
    car switch
    {
        { Year: >= 2020 } => "New car",
        { Make: "Toyota", Model: "Corolla" } => "Toyota Corolla",
        _ => "Old car"
    };

C# Pattern Matching Examples

Pattern matching can be used to simplify complex conditional logic. Here’s a basic example:

 

int value = 44;
string description = value switch
{
    < 0 => "Negative",
    >= 0 and <= 10 => "Between 0 and 10",
    _ => "Greater than 10"
};

C# Pattern Matching Multiple Values

Combining pattern matching with tuples allows for matching against multiple values simultaneously:

 

var point = (x: 3, y: 5);
var position = point switch
{
    (0, 0) => "Origin",
    var (x, y) when x == y => "On the diagonal",
    _ => "Somewhere else"
};

C# Pattern Matching String Contains

Pattern matching can be extended to strings, though directly matching a substring isn't supported in switch expressions. Instead, you can use when clauses:

 

string text = "hello world";
string result = text switch
{
    var t when t.Contains("hello") => "Greeting found",
    _ => "No greeting"
};

C# Pattern Matching Type Switch

Pattern matching with types simplifies type checks and casts:

 

object obj = 42;
var response = obj switch
{
    int i => $"Integer: {i}",
    string s => $"String: {s}",
    _ => "Unknown type"
};

C# Pattern Matching Performance

Pattern matching is typically as performant as equivalent if-else blocks. However, the actual performance can depend on the complexity of the patterns and the types involved.

C# Pattern Matching Generic Type

Pattern matching does not directly support generics due to type erasure at runtime, but you can match generic types by matching the containing type or using methods within the generic class:

 

public void Process<T>(T input)
{
    var type = input switch
    {
        int i => "Integer",
        _ => "Other"
    };
}

C# List Pattern Matching

C# 9.0 and later support list patterns, which can match elements in a collection:

 

var numbers = new[] { 1, 2, 3 };
string matchResult = numbers switch
{
    [1, 2, 3] => "Exact match",
    [1, .., 3] => "Starts with 1 and ends with 3",
    _ => "No match"
};

Pattern matching in C# provides a powerful, readable, and concise way to express complex decision logic. It significantly enhances the language's capabilities, making code easier to write, read, and maintain.


 

Leave a reply Your email address will not be published. Required fields are marked*

Categories Clouds