0Pricing
C# Academy · レッスン

switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)

従来のswitchとreturnを使うメソッドでswitch式を再現し、ガードチェックを追加し、defaultで例外をスローして未処理のケースを実行時に検出します。

「switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)」はCoddyKit上の無料C# Academyレッスンです。 これはレッスン2/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはC# Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 C# Academyコースには全3レッスンが含まれています。

計画: switch のエミュレーション

目標: C# 6 で現代的な switch 式を再現します。

  • 従来の switch から値を返します
  • ガードで事前に確認します
  • 網羅性を確保するため、default throw で早期に失敗させます

値を返す switch

値を返すswitchは、switch expressionのように動作します。default throwで未知の値を捕捉します。

using System;

public enum Grade { A, B, C, D, F }

public class Program
{
  static string Describe(Grade g)
  {
    switch (g)
    {
      case Grade.A: return "Excellent";
      case Grade.B: return "Good";
      case Grade.C: return "Average";
      case Grade.D: return "Below average";
      case Grade.F: return "Fail";
      default: throw new ArgumentOutOfRangeException("g");
    }
  }

  public static void Main(string[] args)
  {
    Console.WriteLine(Describe(Grade.A));
    Console.WriteLine(Describe(Grade.F));
  }
}

「when」をガードで表現

ガードチェック(if)を使ってwhen句を再現します。まず入力を検証し、その後範囲に応じて分岐します。

using System;

public class Program
{
  // Emulate: switch(score) { case var s when s >= 90: ... } using pre-guards
  static string LabelScore(int score)
  {
    if (score < 0 || score > 100) throw new ArgumentOutOfRangeException("score");

    if (score >= 90) return "A";
    if (score >= 80) return "B";
    if (score >= 70) return "C";
    if (score >= 60) return "D";
    return "F";
  }

  public static void Main(string[] args)
  {
    Console.WriteLine(LabelScore(92)); // A
    Console.WriteLine(LabelScore(77)); // C
  }
}

網羅性ヘルパー

小さなExhaustive.Unhandledヘルパーを追加し、defaultで呼び出します。新しい enum 値が処理されていない場合、テストが失敗します。

using System;

public enum Status { New, Active, Closed }

public static class Exhaustive
{
  public static Exception Unhandled(object x)
  {
    return new InvalidOperationException("Unhandled case: " + x);
  }
}

public class Program
{
  static int ToHttp(Status s)
  {
    switch (s)
    {
      case Status.New: return 201;
      case Status.Active: return 200;
      case Status.Closed: return 410;
      default: throw Exhaustive.Unhandled(s);
    }
  }

  public static void Main(string[] args)
  {
    Console.WriteLine(ToHttp(Status.Active)); // 200
  }
}

ガード+kindによるswitch

事前ガードで分岐ごとのデータを検証し、その後判別子でswitchします。これはケースに対する「when」を再現する方法です。

using System;

public enum ShapeKind { Circle, Square }

public sealed class Shape
{
  public ShapeKind Kind;
  public double Radius; // for circle
  public double Side;   // for square
}

public class Program
{
  static double Area(Shape s)
  {
    if (s == null) throw new ArgumentNullException("s");

    // “when” guards (validate needed fields)
    if (s.Kind == ShapeKind.Circle && s.Radius < 0) throw new ArgumentException("Radius must be >= 0");
    if (s.Kind == ShapeKind.Square && s.Side < 0) throw new ArgumentException("Side must be >= 0");

    switch (s.Kind)
    {
      case ShapeKind.Circle: return Math.PI * s.Radius * s.Radius;
      case ShapeKind.Square: return s.Side * s.Side;
      default: throw new InvalidOperationException("Unhandled shape: " + s.Kind);
    }
  }

  public static void Main(string[] args)
  {
    Shape c = new Shape { Kind = ShapeKind.Circle, Radius = 2.0 };
    Console.WriteLine("Area circle = " + Area(c));
  }
}

ヒントと注意点

ヒント:

  • 小さな値を返すメソッド(単一責任)を優先します
  • 不足しているケースを早期に明らかにするため、defaultでは例外をスローするようにします
  • switchの前にガードを置きます。ガードはwhen条件のように機能します

網羅性の再現

確認問題: C# 6で、whenを使うswitch expressionと同様の網羅的なswitch処理を再現するにはどうすればよいですか?

振り返り

振り返り: switch expressionのように従来のswitchから値を返し、ガードで「when」を追加し、未処理のケースを明らかにするためdefault throwを維持します。

よくある質問

「switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)」レッスンは無料ですか?

はい。「switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、C# Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 C# Academyコースには全3レッスンが含まれています。

「switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)」で何を学びますか?

従来のswitchとreturnを使うメソッドでswitch式を再現し、ガードチェックを追加し、defaultで例外をスローして未処理のケースを実行時に検出します。 ブラウザで直接実行するハンズオンコードでC# Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

C# Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのC# Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/3です。

「switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このC# Academyレッスンでコードを書いて実行できますか?

はい。すべてのC# Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. isパターン、関係パターンと論理パターン(C# 6でのエミュレーション)
  2. switch式とwhenによる網羅性チェック(C# 6でのエミュレーション)
  3. 判別共用体(record)によるドメインモデリング — C# 6でのエミュレーション
← C# Academyに戻る