C# Topics (Pattern matching)

Pattern matching

switch (aa)
{
    case {val:12}:
        Console.WriteLine("hello");
        break;
    case A aaa when aa.val2==13:
        Console.WriteLine(aaa.val);
        break;
}

Simplifying switch statements with switch expressions


Animal animal = new Animal() { Name = "tiger" };
string message = animal switch
{
    Animal fourLeggedCat when fourLeggedCat.Name=="cat"
        => $"small cat",
    Animal wildCat when wildCat.Name == "tiger"
        => $"big cat",
};
Console.WriteLine($"switch expression: {message}");

class Animal
{
    public string Name { get; set; }
}

with array patterns

int[] mm = new[]{1,2,3,4,5,6,7};
string vv=mm switch
{
    int[] vvv when mm is [_,2,_,4,..] => "one",
    int[] vvv when mm is {Length: 2} => "two"
};
Console.WriteLine(vv);


int[] mm = new[]{1,2,3,4,5,6,7};
string vv=mm switch
{
    [_,2,_,4,..] => "one",
    {Length: 2} => "two"
};
Console.WriteLine(vv);

relational patterns


bool b=v is (> 32) and (< 66);
string WaterState(int tempInFahrenheit) =>
    tempInFahrenheit switch
    {
        (> 32) and (< 212) => "liquid",
        < 32 => "solid",
        > 212 => "gas",
        32 => "solid/liquid transition",
        212 => "liquid / gas transition",
    };

var m=(12,44);
var l=new{val1=12,val2=44};
bool res=m is {Item1:12,Item2:_};
bool res2=l is {val1:12,val2:_};
Console.WriteLine($" m is {m}, and l is{l}");