How to convert a C# enum to a string

In C#, you can convert an enum to a string using the ToString() method. Here is an example.

enum Color
{
    Red,
    Blue,
    Green
}

Color color = Color.Blue;
string colorString = color.ToString();

Console.WriteLine(colorString); // 输出 "Blue"

You can also use the Enum.GetName() method to retrieve the name of an enum member:

enum Color
{
    Red,
    Blue,
    Green
}

Color color = Color.Green;
string colorString = Enum.GetName(typeof(Color), color);

Console.WriteLine(colorString); // 输出 "Green"

It’s important to note that the names of enum members are different from their string values. If you need to access the string value of an enum member, you can use the Enum.GetValues() method to iterate through the enum, and then use the ToString() method to convert each enum member to a string. Here is an example:

enum Color
{
    [Description("红色")]
    Red,
    [Description("蓝色")]
    Blue,
    [Description("绿色")]
    Green
}

Color color = Color.Blue;
string colorString = GetEnumDescription(color);

Console.WriteLine(colorString); // 输出 "蓝色"

// 获取枚举成员的描述
public static string GetEnumDescription(Enum value)
{
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                                          .SingleOrDefault() as DescriptionAttribute;

    return attribute != null ? attribute.Description : value.ToString();
}

In the example above, we used a DescriptionAttribute attribute to add a description for each enumeration member. Then, we obtained the description value of the enumeration member through reflection.

bannerAds