Getting attributes of Enum's value

get enum value from display name c#
c# enum multiple attributes
c# enum display text
enum attributes java
c# enum string
c# enum string value with space
c# check if enum has attribute
how to get enum value in c#

I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following enum:

using System.ComponentModel; // for DescriptionAttribute

enum FunkyAttributesEnum
{
    [Description("Name With Spaces1")]
    NameWithoutSpaces1,    
    [Description("Name With Spaces2")]
    NameWithoutSpaces2
}

What I want is given the enum type, produce 2-tuples of enum string value and its description.

Value was easy:

Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
foreach (int value in values)
    Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value);

But how do I get description attribute's value, to populate Tuple.Desc? I can think of how to do it if the Attribute belongs to the enum itself, but I am at a loss as to how to get it from the value of the enum.

This should do what you need.

var enumType = typeof(FunkyAttributesEnum);
var memberInfos = enumType.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == enumType);
var valueAttributes = 
      enumValueMemberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
var description = ((DescriptionAttribute)valueAttributes[0]).Description;

Getting the value of a custom attribute from an enum, It should always be in the form AttributeNameAttribute . Enum values should be in CamelCase. And it is common to name classes containing extension methods to be named the same as the class it is extending followed by Extensions . Otherwise, that's pretty much how you'd get custom attributes of a field. Attributes are a mechanism for adding metadata. Reflection is the process by which a program can read its own metadata. This article shows how to add attributes to an enum, and how to read out the attributes via Reflection. I'll cover the following topics in the code samples below: Attribute and Enum.

This piece of code should give you a nice little extension method on any enum that lets you retrieve a generic attribute. I believe it's different to the lambda function above because it's simpler to use and slightly - you only need to pass in the generic type.

public static class EnumHelper
{
    /// <summary>
    /// Gets an attribute on an enum field value
    /// </summary>
    /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
    /// <param name="enumVal">The enum value</param>
    /// <returns>The attribute of type T that exists on the enum value</returns>
    /// <example>string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;</example>
    public static T GetAttributeOfType<T>(this Enum enumVal) where T:System.Attribute
    {
        var type = enumVal.GetType();
        var memInfo = type.GetMember(enumVal.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
        return (attributes.Length > 0) ? (T)attributes[0] : null;
    }
}

Giving an Enum a String Value Using the Description Attribute , When working with enums in C#, it is sometimes necessary to get a string description of the value associated with the enum. This can be  I’d like to present a fairly simple yet useful approach to giving these enums descriptions. * First, we need to reference and import System.ComponentModel. using System.ComponentModel; Next, we decorate our enums with description attributes, setting their desired description where it varies from the enum name.

This is a generic implementation using a lambda for the selection

public static Expected GetAttributeValue<T, Expected>(this Enum enumeration, Func<T, Expected> expression)
    where T : Attribute
{
    T attribute =
      enumeration
        .GetType()
        .GetMember(enumeration.ToString())
        .Where(member => member.MemberType == MemberTypes.Field)
        .FirstOrDefault()
        .GetCustomAttributes(typeof(T), false)
        .Cast<T>()
        .SingleOrDefault();

    if (attribute == null)
        return default(Expected);

    return expression(attribute);
}

Call it like this:

string description = targetLevel.GetAttributeValue<DescriptionAttribute, string>(x => x.Description);

C#, To get the enumeration elements names, we will iterate over the names of the a string with the friendly names (description attributes) of enum appended. It should always be in the form AttributeName Attribute. Enum values should be in CamelCase. And it is common to name classes containing extension methods to be named the same as the class it is extending followed by Extensions. Otherwise, that's pretty much how you'd get custom attributes of a field.

I've merged a couple of the answers here to create a little more extensible solution. I'm providing it just in case it's helpful to anyone else in the future. Original posting here.

using System;
using System.ComponentModel;

public static class EnumExtensions {

    // This extension method is broken out so you can use a similar pattern with 
    // other MetaData elements in the future. This is your base method for each.
    public static T GetAttribute<T>(this Enum value) where T : Attribute {
        var type = value.GetType();
        var memberInfo = type.GetMember(value.ToString());
        var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
        return attributes.Length > 0 
          ? (T)attributes[0]
          : null;
    }

    // This method creates a specific call to the above method, requesting the
    // Description MetaData attribute.
    public static string ToName(this Enum value) {
        var attribute = value.GetAttribute<DescriptionAttribute>();
        return attribute == null ? value.ToString() : attribute.Description;
    }

}

This solution creates a pair of extension methods on Enum. The first allows you to use reflection to retrieve any attribute associated with your value. The second specifically calls retrieves the DescriptionAttribute and returns it's Description value.

As an example, consider using the DescriptionAttribute attribute from System.ComponentModel

using System.ComponentModel;

public enum Days {
    [Description("Sunday")]
    Sun,
    [Description("Monday")]
    Mon,
    [Description("Tuesday")]
    Tue,
    [Description("Wednesday")]
    Wed,
    [Description("Thursday")]
    Thu,
    [Description("Friday")]
    Fri,
    [Description("Saturday")]
    Sat
}

To use the above extension method, you would now simply call the following:

Console.WriteLine(Days.Mon.ToName());

or

var day = Days.Mon;
Console.WriteLine(day.ToName());

EnumMemberAttribute Class (System.Runtime.Serialization , Then apply the EnumMemberAttribute attribute to each member that needs to be Retrieves the type information for an object, which can be used to get the type  To use EnumMemberAttribute, create an enumeration and apply the DataContractAttribute attribute to the enumeration. Then apply the EnumMemberAttribute attribute to each member that needs to be in the serialization stream.

In addition to AdamCrawford response, I've further created a more specialized extension methods that feed of it to get the description.

public static string GetAttributeDescription(this Enum enumValue)
{
    var attribute = enumValue.GetAttributeOfType<DescriptionAttribute>();
    return attribute == null ? String.Empty : attribute.Description;
} 

hence, to get the description, you could either use the original extension method as

string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description

or you could simply call the the extension method here as:

string desc = myEnumVariable.GetAttributeDescription();

Which should hopefully make your code a bit more readable.

ParameterAttributes Enum (System.Reflection), This enumeration has a FlagsAttribute attribute that allows a bitwise combination of GetParameters(); // Get and display the attributes for the second parameter. Retrieves an array of the values of the constants in a specified enumeration. ///This is used to get Enum values as array. private static void GetEnumValues() { Array enumValueArray = Enum.GetValues(typeof(MicrosoftOffice)); foreach (int enumValue in enumValueArray) {

How To Play With Enum in C#, How to get enum variable name by its value in C#? This is used to set the Custom string to the enum variable as an attribute and get the  The above will throw an exception if you call it with an Enum that has a mix of custom attributes and plain items, e.g. public enum CommentType { All = 1, Rent = 2, Insurance = 3, [Display(Name="Service Charge")] ServiceCharge = 4 }

Getting Enum descriptions using C#, Accessing Enum descriptions isn't complicated. Let's review an elegant solution using attributes, extension methods and C#. Photo by Emre  Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this: string enumDesc = MyEnum.HereIsAnother.DescriptionAttr(); string classDesc = myInstance.SomeProperty.DescriptionAttr();

Get attribute of enum | C# Online Compiler, Get attribute of enum | Test your C# code online with .NET Fiddle code editor. Giving an Enum a String Value Using the Description Attribute Published Mar 27, 2017 Last updated Oct 11, 2018 When working with enums in C#, it is sometimes necessary to get a string description of the value associated with the enum.

Comments
  • From another question stackoverflow.com/questions/469287/…
  • possible duplicate of Anyone know a quick way to get to custom attributes on an enum value?
  • namespace required for Description is System.ComponentModel
  • You can also just not use System.ComponentModel and just use your own attribute type; there's really nothing all that special about DescriptionAttribute.
  • plesae see this link : stackoverflow.com/a/58954215/5576498
  • Optionally use type.GetFields(BindingFlags.Public | BindingFlags.Static) to get all the memInfos at once.
  • I had to go typeof(FunkyAttributesEnum), but other than that it worked well. Thanks.
  • @AlexK I don't see Enum class has a NameWithoutSpaces1 property. Where does the FunkyAttributesEnum.NameWithoutSpaces1 come from?
  • @Don, it's the enum member name from the OP's question.
  • Usage would then be: string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;
  • I like this one more than Scott's, because the usage is cleaner here (less typing), so +1 :)
  • If no attribute exists, wouldn't this throw a IndexOutOfRangeException?
  • better use type.GetMember(Enum.GetName(type, enumVal)) for the memInfo as enumVal.ToString() may not be reliable for different locales.
  • What is the point of calling GetCustomAttributes() then get first element instead of calling GetCustomAttribute() ?