動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン5: Parse / TryParse + IsDefinedでDB値検証

出典: C# Enum 完全ガイド — Description 属性 / [Flags] / 数値変換の使い分け5パターンパターン5: Parse / TryParse + IsDefinedでDB値検証

パターン5: Parse / TryParse + IsDefinedでDB値検証 (csharp)#89bad7c4a5ae
using System;
 
public enum ProductStatus
{
    Active = 1,
    Suspended = 2,
    Discontinued = 9
}
 
class Program
{
    static void Main()
    {
        //文字列→ Enum変換(DBの文字列カラムから読み込み)
        string dbStringValue = "Active";
 
        // ✅ TryParseで安全に変換(ignoreCase: trueで大文字小文字無視)
        if (Enum.TryParse<ProductStatus>(dbStringValue, ignoreCase: true, out var status))
        {
            Console.WriteLine($"変換成功: {status}");
        }
        else
        {
            Console.WriteLine("変換失敗");
        }
 
        //数値→ Enum変換+ IsDefinedで検証
        int dbIntValue = 999;  // DBに想定外の値が入ってた
 
        if (Enum.IsDefined(typeof(ProductStatus), dbIntValue))
        {
            var statusFromInt = (ProductStatus)dbIntValue;
            Console.WriteLine($"検証OK: {statusFromInt}");
        }
        else
        {
            Console.WriteLine($"未定義の値: {dbIntValue}");
            //エラーログ/デフォルト値処理など
        }
    }
}
▸ 実行ボタンで結果を表示
  • id: #89bad7c4a5ae
  • lines: 41
  • extracted: 2026-06-10
  • captured: 2026-06-04

Source収録記事

この snippet は記事の「パターン5: Parse / TryParse + IsDefinedでDB値検証」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

7
図鑑トップ