Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum Description to String

Tags:

c#

enums

I have the following ENUM:

[Flags]
public enum DataFiat {

  [Description("Público")]
  Public = 1,

  [Description("Filiado")]
  Listed = 2,

  [Description("Cliente")]
  Client = 4

} // DataFiat

And I created an extension to get an Enum attribute:

public static T GetAttribute<T>(this Enum value) where T : Attribute {

  T attribute;
  MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
  if (info != null) {
    attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
    return attribute;
  }
  return null;
}

This works for non Flags Enums ... But when I have:

var x = DataFiat.Public | DataFiat.Listed;
var y = x.GetAttribute<Description>();

The value of y is null ...

I would like to get "Público, Filiado, Cliente" ... Just as ToString() works.

How can I change my extension to make this work?

Thank You

like image 443
Miguel Moura Avatar asked Feb 19 '14 14:02

Miguel Moura


2 Answers

You can use this:

var values = x.ToString()
             .Split(new[] { ", " }, StringSplitOptions.None)
             .Select(v => (DataFiat)Enum.Parse(typeof(DataFiat), v));

To get the individual values. Then get the attribute values of them.

Something like this:

var y2 = values.GetAttributes<DescriptionAttribute, DataFiat>();

public static T[] GetAttributes<T, T2>(this IEnumerable<T2> values) where T : Attribute
{
    List<T> ts =new List<T>();

    foreach (T2 value in values)
    {
        T attribute;
        MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
        if (info != null)
        {
            attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
            ts.Add(attribute);
        }
    }

    return ts.ToArray();
}
like image 94
Patrick Hofman Avatar answered Oct 04 '22 23:10

Patrick Hofman


in .NET CORE without any additional libraries you can do:

 public enum Divisions
 {
    [Display(Name = "My Title 1")]
    None,
    [Display(Name = "My Title 2")]
    First,
 }

and to get the title:

using System.ComponentModel.DataAnnotations
using System.Reflection

string title = enumValue.GetType()?.GetMember(enumValue.ToString())?[0]?.GetCustomAttribute<DisplayAttribute>()?.Name;
like image 34
TheAccessMan Avatar answered Oct 04 '22 22:10

TheAccessMan