Featured Post

Organize and rename photos by EXIF data with PowerShell

This PowerShell script organizes and renames all photos in a selected folder using EXIF data. It will also create thumbnails of the images i...

Monday, November 4, 2013

(C#) Friendly names for enums

Enums are quick and easy. Here is how to have a friendly name for your enum value to display on the UI.

public enum CustomEnum
{
    [System.ComponentModel.Description("I am Alpha")]
    Alpha,
    [System.ComponentModel.Description("Beta Friendly Label")]
    Beta
}

public static class EnumHelper
{
    public static string GetEnumDescription(Enum value)
    {
        System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());

        System.ComponentModel.DescriptionAttribute[] attributes =
            (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(System.ComponentModel.DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
        {
            return attributes[0].Description;
        }
        else
        {
            return value.ToString();
        }
    }
}

Usage:
MessageBox.Show(EnumHelper.GetEnumDescription(CustomEnum.Alpha));

No comments:

Post a Comment