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
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();
}
                        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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With