C#•型キャスト
C# の型キャスト:int.TryParse・as・is パターンマッチング
TryParse による防御的パースと、モダンな C# の is 型パターンを使った安全なダウンキャストを学びます。
構文
if (int.TryParse(str, out int val)) {}
if (obj is string s) {}
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| TryParse | Method | 例外を投げずにパース成功を示す真偽値を返します。 |
| is Pattern | C# Feature | 1 ステップで型を判定し新しい型付き変数を束縛します。 |
そのまま実行できるコード例
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#チュートリアルとコンパイラ
C# の強い型付け暗黙的 var 代入とデータ型
暗黙的型推論 var、プリミティブ型(int, double, decimal, bool)、書式指定子による C# の静的型付けを学びます。
C# 演算子:Null 条件 (?.) と Null 合体 (??)
C# の算術・比較演算子、Null 条件演算子 (?.)、Null 合体演算子 (??) を習得します。
C# のパターンマッチング switch 文と switch 式
関係範囲、論理コンビネータ (and/or)、破棄ガードを備えたモダンな C# パターンマッチング switch 式 (=>) を実装します。
C# オンラインコンパイラ
Compilra IDE で開く