CSharp - switch with patterns

Introduction

Normal switch statement matches case by constant value.

C# switch can match case by a type, and after matching you can assign a value to the variable.

There's no restriction on what types you can use.

Demo

using System;
class MainClass/*from  w  w  w .  j a  v a2s . c  om*/
{
    public static void Main(string[] args)
    {
        TellMeTheType(12);
        TellMeTheType("hello");
        TellMeTheType(true);

    }
    static void TellMeTheType(object x)   // object allows any type.
    {
        switch (x)
        {
            case int i:
                Console.WriteLine("int:" + i);
                break;
            case string s:
                Console.WriteLine("string:" + s.Length);
                break;
            default:
                Console.WriteLine("unknown");
                break;
        }
    }

}

Result

Related Topics