C# language feature:

  • Pattern matching

applies to

  • switch statement, is expressions

benefit

  • Allows testing for pattern/type and extracting as type.

how to use

  • 1) In is statement, insert type after is followed by variable identifier, use variable in statement as desired.
  • 2) In switch statement, insert type after case followed by variable identifier, use variable in case statement as desired.

example:

        void Is_Pattern_Matching_Example(object object2check)
        {
            if (object2check is int i || (object2check is string s && int.TryParse(s, out i)))
                System.Console.WriteLine($"the int is {i}");
            else
                System.Console.WriteLine("not an int or parsable string");
        }
        void Switch_Pattern_Matching_Example(object object2check)
        {
            switch (object2check)
            {
                case int i:
                    System.Console.WriteLine($"object is an integer with value {i}");
                    break;
                case string s:
                    System.Console.WriteLine($"object is a string ({s}) and has {s.Length} character(s)");
                    break;
                default:
                    System.Console.WriteLine("object is something other than int or string");
                    break;
                case null:
                    System.Console.WriteLine("object is null");
                    break;
            }
        }