//商品ステータスのEnum
public enum ProductStatus
{
Active = 1, //販売中
Suspended = 2, //一時停止
Discontinued = 9 //廃番
}
//使い方
class Program
{
static void Main()
{
// Enum → intキャスト(DB保存用)
int dbValue = (int)ProductStatus.Active; // 1
// int → Enumキャスト(DB読み込み用)
var status = (ProductStatus)1; // ProductStatus.Active
//比較
if (status == ProductStatus.Active)
{
Console.WriteLine("販売中の商品");
}
// ToString()で名前取得
string name = status.ToString(); // "Active"
}
}
▸ 実行ボタンで結果を表示
Source収録記事
この snippet は記事の「パターン1:基本宣言と数値変換」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
7 件if (status == 1){ /* 販売中 */ } else if (status == 2){ /* 一時停止 */ } else if (status == 9){ /* 廃番 */ }未収録
if (status == 1){ /* 販売中 */ }
#e9dce50030d4
using System; using System.ComponentModel; using System.Reflection;
▶ 実行可
パターン2: Description属性で画面表示
#b083bdc7c698
//キャッシュ版 public static class EnumDescriptionCache { private static readonly Dictionary<Enum, string> _cache = new Dictionary<Enum, string>();未収録
パターン2: Description属性で画面表示
#9ca736d259fd
using System; [Flags] public enum Permission
▶ 実行可
パターン3: [Flags]属性でビット組合せ
#55cfcc401bc8
using System; using System.Linq; using System.Windows.Forms;未収録
パターン4: GetValues / GetNamesでComboBoxバインド
#d673233cfac5
using System; public enum ProductStatus {
▶ 実行可
パターン5: Parse / TryParse + IsDefinedでDB値検証
#89bad7c4a5ae
![C# Enum 完全ガイド — Description 属性 / [Flags] / 数値変換の使い分け5パターン](/_next/image/?url=https%3A%2F%2Fhiropon-progra.com%2Fwp-content%2Fuploads%2F2026%2F05%2Fcsharp-enum-complete-guide.png&w=3840&q=75)