Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

C# enum key value

public enum infringementCategory
{ 
    [Description("INF0001")]
    Infringement,
    [Description("INF0002")]
    OFN
}

public static class EnumExtension
{
    /// <summary>
    /// Gets the string of an DescriptionAttribute of an Enum.
    /// </summary>
    /// <param name="value">The Enum value for which the description is needed.</param>
    /// <returns>If a DescriptionAttribute is set it return the content of it.
    /// Otherwise just the raw name as string.</returns>
    public static string Description(this Enum value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        string description = value.ToString();
        FieldInfo fieldInfo = value.GetType().GetField(description);
        DescriptionAttribute[] attributes =
           (DescriptionAttribute[])
         fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
        {
            description = attributes[0].Description;
        }

        return description;
    }

    /// <summary>
    /// Creates an List with all keys and values of a given Enum class
    /// </summary>
    /// <typeparam name="T">Must be derived from class Enum!</typeparam>
    /// <returns>A list of KeyValuePair<Enum, string> with all available
    /// names and values of the given Enum.</returns>
    public static IList<KeyValuePair<Enum, string>> ToList<T>() where T : struct
    {
        var type = typeof(T);

        if (!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }

        return (IList<KeyValuePair<Enum, string>>)
                Enum.GetValues(type)
                    .OfType<Enum>()
                    .Select(e => new KeyValuePair<Enum, string>(e, e.Description()))
                    .ToArray();
    }

    public static T GetValueFromDescription<T>(string description) where T : struct
    {
        var type = typeof(T);

        if(!type.IsEnum)
        {
            throw new ArgumentException("T must be an enum");
        }

        foreach(var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;

            if(attribute != null)
            {
                if(attribute.Description == description)
                {
                    return (T)field.GetValue(null);
                }
            }
            else
            {
                if(field.Name == description)
                {
                    return (T)field.GetValue(null);
                }
            }
        }

        throw new ArgumentOutOfRangeException("description");
        // or return default(T);
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: how to do division with button C# 
Csharp :: Working with null values 
Csharp :: c# XmlElement from string 
Csharp :: C# decimal built-in methods 
Csharp :: data types of document in asp dot net frame work 
Csharp :: c# check value at design time 
Csharp :: How to change color of a column in RDLC report 
Csharp :: c# UserControl make background transparent 
Csharp :: hash sign c sharp 
Csharp :: build url mvs view 
Csharp :: get datacontext of itemscontrol item c# 
Csharp :: get 24 hour time in c# 
Csharp :: Click an HTML link inside a WebBrowser Control 
Csharp :: wpf loop through grid rows 
Csharp :: how to pass value to anothe form c# winform 
Csharp :: c# convert float to string 
Csharp :: player movement unity 3d script 
Csharp :: opération inter-threads non valide 
Csharp :: salary, overtime, deductions, gross pay and netpay in console C# 
Csharp :: Getting the ID of the element that fired an event 
Csharp :: c# Difference Array | Range update query in O(1) 
Csharp :: what error code i should return in asp.net core whether user name or password are incorrect 
Csharp :: how to make game restart when player touches a object unity 
Csharp :: button next for picturebox c# 
Csharp :: check which activity in focus in android 
Csharp :: Razor switch statement 
Csharp :: ienumerable tolist 
Csharp :: c# convert linq jValue to int 
Csharp :: httprequestmessage with authorization .net 5 
Csharp :: what loops are entry controlled c# 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =