C#:C# の型キャスト:int.TryParse・as・is パターンマッチング
C#•型キャスト

C# の型キャスト:int.TryParse・as・is パターンマッチング

TryParse による防御的パースと、モダンな C# の is 型パターンを使った安全なダウンキャストを学びます。

構文

if (int.TryParse(str, out int val)) {} if (obj is string s) {}

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
TryParseMethod例外を投げずにパース成功を示す真偽値を返します。
is PatternC# Feature1 ステップで型を判定し新しい型付き変数を束縛します。

そのまま実行できるコード例

Compilra で実行可能

C# をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

using System;

public class Program {
    public static void Main() {
        // 1. Safe TryParse (never throws exception)
        string rawPort = "8080";
        if (int.TryParse(rawPort, out int portNumber)) {
            Console.WriteLine($"Successfully parsed port: {portNumber}");
        }

        // 2. Type Pattern Matching with is
        object dataPayload = "compilra_secure_session_token";
        if (dataPayload is string text) {
            Console.WriteLine($"Payload is string (Length: {text.Length}): {text.ToUpper()}");
        }
    }
}
期待される出力:
Successfully parsed port: 8080
Payload is string (Length: 29): COMPILRA_SECURE_SESSION_TOKEN

動作のしくみ: ステップ解説

  • 6-8 行目: int.TryParse が文字列を out 変数 portNumber へ解析します。
  • 12-14 行目: dataPayload is string text が型を判定し text 変数を束縛します。

重要ポイント

  • int.TryParse はコストの高い FormatException の try/catch オーバーヘッドを回避します。
  • C# の is パターンマッチング (obj is Type t) は判定とキャストを同時に行います。

よくある間違い: 信頼できないユーザー入力に対して try/catch なしで int.Parse() を使う

不正な入力に対して int.Parse は FormatException を投げます。代わりに int.TryParse を使用してください。

❌ 誤り
int x = int.Parse("abc"); // Unhandled FormatException crash!
✅ 正しい例
if (int.TryParse("abc", out int x)) { /* Safe */ }

関連するC#チュートリアルとコンパイラ

Compilra で C# を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。

C# オンラインコンパイラ