Get enum from enum attribute

c# enum custom attributes
c# get all attributes of enum
c# reflection get attribute of enum
enum get property
c# enum get property
assign string to enum c#
c# enum tryparse description
getattributeoftype

I've got

public enum Als 
{
    [StringValue("Beantwoord")] Beantwoord = 0,
    [StringValue("Niet beantwoord")] NietBeantwoord = 1,
    [StringValue("Geselecteerd")] Geselecteerd = 2,
    [StringValue("Niet geselecteerd")] NietGeselecteerd = 3,
}

with

public class StringValueAttribute : Attribute
{
    private string _value;

    public StringValueAttribute(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }
}

And I would like to put the value from the item I selected of a combobox into a int:

int i = (int)(Als)Enum.Parse(typeof(Als), (string)cboAls.SelectedValue); //<- WRONG

Is this possible, and if so, how? (the StringValue matches the value selected from the combobox).

Here's a helper method that should point you in the right direction.

protected Als GetEnumByStringValueAttribute(string value)
{
    Type enumType = typeof(Als);
    foreach (Enum val in Enum.GetValues(enumType))
    {
        FieldInfo fi = enumType.GetField(val.ToString());
        StringValueAttribute[] attributes = (StringValueAttribute[])fi.GetCustomAttributes(
            typeof(StringValueAttribute), false);
        StringValueAttribute attr = attributes[0];
        if (attr.Value == value)
        {
            return (Als)val;
        }
    }
    throw new ArgumentException("The value '" + value + "' is not supported.");
}

And to call it, just do the following:

Als result = this.GetEnumByStringValueAttribute<Als>(ComboBox.SelectedValue);

This probably isn't the best solution though as it's tied to Als and you'll probably want to make this code re-usable. What you'll probably want to strip out the code from my solution to return you the attribute value and then just use Enum.Parse as you are doing in your question.

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  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 accomplished easily by using the DescriptionAttribute class. Originally, I was using code like the following to set the string value based on the value of an enum, but it seemed too cumbersome and had to be used everytime I wanted to parse an enum.

I'm using the DescriptionAttribute from Microsoft and the following extension method:

public static string GetDescription(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;
}

Getting the value of a custom attribute from an enum, Make it general purpose using generics. Though I'd strongly suggest you rename your attribute to follow .NET guidelines. It should always be in the form  <Flags> Public Enum Pets As Integer None = 0 Dog = 1 Cat = 2 Rodent = 4 Bird = 8 Fish = 16 Reptile = 32 Other = 64 End Enum The assembly is loaded in a reflection-only context, a Type object that represents the Pets enumeration is instantiated, an array of FieldInfo objects is retrieved, and the field values are displayed to the console.

Here are a couple extension methods that I use for this exact purpose, I've rewritten these to use your StringValueAttribute, but like Oliver I use the DescriptionAttribute in my code.

    public static T FromEnumStringValue<T>(this string description) where T : struct {
        Debug.Assert(typeof(T).IsEnum);

        return (T)typeof(T)
            .GetFields()
            .First(f => f.GetCustomAttributes(typeof(StringValueAttribute), false)
                         .Cast<StringValueAttribute>()
                         .Any(a => a.Value.Equals(description, StringComparison.OrdinalIgnoreCase))
            )
            .GetValue(null);
    }

This can be made slightly more simple in .NET 4.5:

    public static T FromEnumStringValue<T>(this string description) where T : struct {
        Debug.Assert(typeof(T).IsEnum);

        return (T)typeof(T)
            .GetFields()
            .First(f => f.GetCustomAttributes<StringValueAttribute>()
                         .Any(a => a.Value.Equals(description, StringComparison.OrdinalIgnoreCase))
            )
            .GetValue(null);
    }

And to call it, just do the following:

Als result = ComboBox.SelectedValue.FromEnumStringValue<Als>();

Conversely, here's a function to get the string from an enum value:

    public static string StringValue(this Enum enumItem) {
        return enumItem
            .GetType()
            .GetField(enumItem.ToString())
            .GetCustomAttributes<StringValueAttribute>()
            .Select(a => a.Value)
            .FirstOrDefault() ?? enumItem.ToString();
    }

And to call it:

string description = Als.NietBeantwoord.StringValue()

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  Remarks. The EnumMemberAttribute enables fine control of the names of the enumerations as they are serialized. 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.

Not sure if I am missing something here, can you not do this,

Als temp = (Als)combo1.SelectedItem;
int t = (int)temp;

TylerBrinkley/Enums.NET: Enums.NET is a high , Enums.NET is a high-performance type-safe .NET enum utility library Field)] class SymbolAttribute : Attribute { public string Symbol { get; } public  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.

Coming here from duplicate links of this highly upvoted question and answer, here is a method that works with C# 7.3's new Enum type constraint. Note that you also need to specify that it is also a struct so that you can make it the nullable TEnum? or else you will get an error.

public static TEnum? GetEnumFromDescription<TEnum>(string description)
    where TEnum : struct, Enum 
{
    var comparison = StringComparison.OrdinalIgnoreCase;
    foreach (var field in typeof(TEnum).GetFields())
    {
        var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        if (attribute != null)
        {
            if (string.Compare(attribute.Description, description, comparison) == 0)
                return (TEnum)field.GetValue(null);
        }
        if (string.Compare(field.Name, description, comparison) == 0)
            return (TEnum)field.GetValue(null);
    }
    return null;
}

Enum.Parse Method (System), An object of type enumType whose value is represented by value . Attributes. ComVisibleAttribute. Exceptions. ArgumentNullException. enumType or value is null  Extending Enums with Custom Attributes. Sometimes we are too lazy to create a class. Enumerations are very simple to create and use but they haven't any properties or fields. So, we can only add custom attributes (I used strings, but it's possible to use more complex types).

Attaching Values to Java Enum, Java provides a valueOf(String) method for all enum types. Thus, we can always get an enum value based on the declared name: ? 1. C# Tips and Tricks #2 – How to Get the Description Attribute Value of Enum in C# ? June 14, 2015 Senthil Kumar B CSharp No comments There are times when you want to get the attributes of the enum values from your C# cod e for some display purpose .

enum — Support for enumerations, The attributes Color.RED , Color.GREEN , etc., are enumeration members (or enum members) and are functionally constants. The enum members have names​  First create a sample set of enum variables. Then, create a custom attribute class for just custom String Value. Create an extension method for just enum. Use the extension method to get just enum custom string value. 1. Enum variable for custom String value in C#:

C# stuff nobody told you – enum is a b*tch! – A Girl Among Geeks, To fully understand the situation, have a look at the method below. It just reads the enum description straight from the [Description] attribute. An enum can, just like a class, have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Comments
  • That should work. What's the problem?
  • Random tip: You can use auto properties for this. use "public string Value { get; private set;} and you can avoid the tacky _value variable.
  • @Kent Boogaart: "Niet beantwoord" != "NietBeantwoord"
  • I think if you keep the itemnames in the enum as the combobox's selectedvalue property then it should work (and I guess you know that). I am now sure why you want the stringvalue attribute you defined as the combobox's selected value. I suppose it is for display purpose.
  • You have to do a loop (or use LINQ for the search) which finds the corresponding enum value to the entered text. Use Oliver's solution to get the Attributes.
  • This solution can easily be changed to be generic. Simply change all occurrences of Als to T and add a type argument named T to the method.
  • @DanielHilgarth I tryied to do it but got error saying "The type parameter cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint" on the return line of the method. Would you have a practical example on how this could be solved?
  • Opposite of what OP asked since he wants enum from string and not string from enum, but that helped me a lot, thanks!