2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でEnumのDescriptionを使ってみる

Posted at

1. はじめに

  • C# でEnum型を使用する時に同時に文字列も定義したい
  • Enum型のDescription属性を使用して解決したい

2. 開発環境

  • C#
  • .Net 6
  • Visual Studio 2022
  • Windows 11

3. Enum型を定義する

using System.ComponentModel;

public  class SampleEnum
{
    public enum CityEnum
    {
        [Description("東京")]
        Tokyo = 1,

        [Description("大阪")]
        Nagoya = 2,

        [Description("名古屋")]
        Sapporo = 3,
    }
}

4. Enum型からDescriptionを取得する

/// <summary>
/// 列挙体フィールドのDescriptionを取得する。
/// </summary>
/// <param name="value">列挙体値</param>
/// <returns>Description文字列</returns>
public static string GetDescription<T>(T value) where T : Enum
{
    string description = string.Empty;

    if (value != null)
    {
        string strValue = value.ToString();

        description = strValue;

        if (strValue.Length > 0)
        {
            FieldInfo? fieldInfo = typeof(T).GetField(strValue);
            if (fieldInfo != null) { 
                Attribute? attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
                if (attribute != null)
                {
                    DescriptionAttribute descriptionAttribute = (DescriptionAttribute)attribute;
                    description = descriptionAttribute.Description;
                }
            }
        }
    }

    return description;
}

5. 参考文献

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?