CSharp - Predicate a case with the when keyword

Introduction

You can predicate a case with the when keyword:

switch (x)
{
     case bool b when b == true:     // Fires only when b is true
         Console.WriteLine ("True!");
         break;
     case bool b:
         Console.WriteLine ("False!");
         break;
}

The default clause is always executed last, regardless of where it appears.

You can stack multiple case clauses.

Demo

using System;
class MainClass// ww w. j  a v a 2s.c o  m
{
   public static void Main(string[] args)
   {
       TellMeTheType (12);
       TellMeTheType ("hello");
       TellMeTheType (true);

   }
     static void TellMeTheType (object x)   // object allows any type.
     {
         switch (x)
         {
           case bool b when b == true:     // Fires only when b is true
             Console.WriteLine ("True!");
             break;
           case bool b:
             Console.WriteLine ("False!");
             break;
         }
     }

}

Result

Related Topic