c# switch when clause code example

Example 1: Type in switch case argument c#

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Example 2: c# switch

using System;

namespace SwitchStatement
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Please write a movie genre.");
      string genre = Console.ReadLine();
      switch (genre)
      {
        case "Drama":
        Console.WriteLine("Citizen Kane");
        break;
        case "Comedy":
        Console.WriteLine("Duck Soup");
        break;
        case "Adventure":
        Console.WriteLine("King Kong");
        break;
        case "Horror":
        Console.WriteLine("Psycho");
        break;
        case "Science Fiction":
        Console.WriteLine("2001: A Space Odyssey");
        break;
        default:
        Console.WriteLine("No movie found.");
        break;
      }
    }
  }
}