Essential C# C# 7.0 Features  Suggest an edit

Pattern Matching

Pattern matching extensions for C# enable many of the benefits of pattern matching from functional languages, but in a way that smoothly integrates with the feel of the underlying language

switch expression

Pattern matching extends the switch statement to switch on types:

class Geometry {} 

class Triangle : Geometry
{
    public int Width { get; set; }
    public int Height { get; set; }
    public int Base { get; set; }
}

class Rectangle : Geometry
{
    public int Width { get; set; }
    public int Height { get; set; }
}

class Square : Geometry
{
    public int Width { get; set; }
}

public static void PatternMatching()
{
    Geometry g = new Square { Width = 5 }; 
    
    switch (g)
    {
        case Triangle t:
            Console.WriteLine($"{t.Width} {t.Height} {t.Base}");
            break;
        case Rectangle sq when sq.Width == sq.Height:
            Console.WriteLine($"Square rectangle: {sq.Width} {sq.Height}");
            break;
        case Rectangle r:
            Console.WriteLine($"{r.Width} {r.Height}");
            break;
        case Square s:
            Console.WriteLine($"{s.Width}");
            break;
        default:
            Console.WriteLine("<other>");
            break;
    }
}

is expression

Pattern matching extends the is operator to check for a type and declare a new variable at the same time.

Example

string s = o as string;
if(s != null)
{
    // do something with s
}

can be rewritten as:

if (o is string s)
{
    //Do something with s
};

Also note that the scope of the pattern variable s is extended to outside the if block reaching the end of the enclosing scope, example:

if (someCondition)
{
   if(o is string s)
   {
      //Do something with s
   }
   else
   {
     // s is unassigned here, but accessible 
   }

   // s is unassigned here, but accessible 
}
// s is not accessible here

Table Of Contents
22 Enum
25 GUID
70 C# 7.0 Features
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close