--- lang: ja-jp breaks: true --- # C# switch セクション内の when 句 2021-07-11 ## case ステートメントおよび when 句 > C# 7.0 以降では、case ステートメントは相互に排他的である必要がないため、when 句を追加して、case ステートメントを true に評価するために満たされなければならない条件を指定できます。 when 句には、ブール値を返す任意の式を指定できます。 > https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/keywords/switch#the-case-statement-and-the-when-clause ```csharp= private static void ShowShapeInfo(Shape sh) { switch (sh) { // Note that this code never evaluates to true. case Shape shape when shape == null: Console.WriteLine($"An uninitialized shape (shape == null)"); break; case null: Console.WriteLine($"An uninitialized shape"); break; case Shape shape when sh.Area == 0: Console.WriteLine($"The shape: {sh.GetType().Name} with no dimensions"); break; case Square sq when sh.Area > 0: Console.WriteLine("Information about square:"); Console.WriteLine($" Length of a side: {sq.Side}"); Console.WriteLine($" Area: {sq.Area}"); break; case Rectangle r when r.Length == r.Width && r.Area > 0: Console.WriteLine("Information about square rectangle:"); Console.WriteLine($" Length of a side: {r.Length}"); Console.WriteLine($" Area: {r.Area}"); break; case Rectangle r when sh.Area > 0: Console.WriteLine("Information about rectangle:"); Console.WriteLine($" Dimensions: {r.Length} x {r.Width}"); Console.WriteLine($" Area: {r.Area}"); break; case Shape shape when sh != null: Console.WriteLine($"A {sh.GetType().Name} shape"); break; default: Console.WriteLine($"The {nameof(sh)} variable does not represent a Shape."); break; } } ``` ###### tags: `C#` `switch` `when`