Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the Value for an EnumMember attribute

Tags:

c#

attributes

public enum Status
    {

        Pending,
        [EnumMember(Value = "In Progress")]
        InProgress,
        Failed,
        Success
    }

string dbValue = "In Progress";
if (dbValue == ValueOf(Status.InProgress)){
//do some thing
}

How do I read the Value of Status.InProgress so I get back "in Progress"?

like image 678
user1830997 Avatar asked Dec 09 '14 06:12

user1830997


People also ask

How do you find the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do I use Enummember?

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.

What is description in enum in C#?

Definition. An Enumeration (or enum ) is a data type that includes a set of named values called elements or members. The enumerator names are usually identifiers that behave as constants in the language.


6 Answers

This is an extension method that works with C# 8 and nullable reference types:

public static string? GetEnumMemberValue<T>(this T value)
    where T : Enum
{
    return typeof(T)
        .GetTypeInfo()
        .DeclaredMembers
        .SingleOrDefault(x => x.Name == value.ToString())
        ?.GetCustomAttribute<EnumMemberAttribute>(false)
        ?.Value;
}

Original Answer:

I've adapted this for .NET Core. Here it is:

public static String GetEnumMemberValue<T>(T value)
    where T : struct, IConvertible
{
    return typeof(T)
        .GetTypeInfo()
        .DeclaredMembers
        .SingleOrDefault(x => x.Name == value.ToString())
        ?.GetCustomAttribute<EnumMemberAttribute>(false)
        ?.Value;
}
like image 186
Christopher Haws Avatar answered Oct 22 '22 04:10

Christopher Haws


Something like this:

public string GetEnumMemberAttrValue(Type enumType, object enumVal)
{
      var memInfo = enumType.GetMember(enumVal.ToString());
      var attr = memInfo[0].GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
      if(attr != null)
      {
          return attr.Value;
      }

      return null;
}

Usage:

var enumType = typeof(Status);
var enumVal = Status.InProgress;
var str = GetEnumMemberAttrValue(enumType,enumVal);
like image 33
Amir Popovich Avatar answered Oct 22 '22 03:10

Amir Popovich


Borrowing from Amir's answer, a slightly nicer version is possible using generics as follows:

public string GetEnumMemberAttrValue<T>(T enumVal)
{
    var enumType = typeof(T);
    var memInfo = enumType.GetMember(enumVal.ToString());
    var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
    if (attr != null)
    {
        return attr.Value;
    }

    return null;
}

Usage as follows:

var enumVal = Status.InProgress;
var str = GetEnumMemberAttrValue(enumVal);

As far as I'm aware T can't be constrained to enum's using a where clause. I would be happy to be corrected though.

like image 15
Wes Avatar answered Oct 22 '22 03:10

Wes


Wrapped it in an extension to make it feel more natural:

public static class Extension
{
    public static string ToEnumMemberAttrValue(this Enum @enum)
    {
        var attr = 
            @enum.GetType().GetMember(@enum.ToString()).FirstOrDefault()?.
                GetCustomAttributes(false).OfType<EnumMemberAttribute>().
                FirstOrDefault();
        if (attr == null)
            return @enum.ToString();
        return attr.Value;
    }
}

Usage:

string dbValue = "In Progress";
if (dbValue == Status.ToEnumMemberAttrValue())){
    //do some thing
}
like image 11
urbanSoft Avatar answered Oct 22 '22 03:10

urbanSoft


If you have Newtonsoft in your project, that is what you should do:

to the Enum, you should add the attribute [JsonConverter(typeof(StringEnumConverter))]

and now you can call the JsonConvertor to serialize your value as the member string value.

in your example, it should be like that

[JsonConverter(typeof(StringEnumConverter))]
public enum Status
{

    Pending,
    [EnumMember(Value = "In Progress")]
    InProgress,
    Failed,
    Success
}

string dbValue = "In Progress";
if (dbValue == JsonConvert.SerializeObject(Status.InProgress)){
//do some thing
}

Note as mentioned by @Dinesh in the comment that the string is JSON therefor return with quatos so you can workaround that to get a clean string with strin.Replace method as:

dbValue == JsonConvert.SerializeObject(Status.InProgress).Replace("\"","");
like image 6
dubi Avatar answered Oct 22 '22 04:10

dubi


    public static object GetMemberAttr(this Enum enumItem)
    {
        var memInfo = enumItem.GetType().GetMember(enumItem.ToString());
        var attr = memInfo[0].GetCustomAttributes(false);
        return attr == null || attr.Length == 0 ? null :((System.Runtime.Serialization.EnumMemberAttribute) attr[0]).Value;
    }

Usage: {YouEnum}.{EnumItem}.GetMemberAttr() public enum TEST_ENUM { [EnumMember(Value = "1min")] Minute, [EnumMember(Value = "2min")] TwoMinutes, [EnumMember(Value = "3min")] ThreeMinutes, }

public TEST_ENUM t;

? t.TwoMinutes.GetMemberAttr()
2min

like image 3
Solarev Sergey Avatar answered Oct 22 '22 03:10

Solarev Sergey