I have two enums, one with flags and another without:
[Flags]
public enum MyEnumWithFlags {
[Description("Item 1")]
Item1 = 1,
[Description("Item 2")]
Item2 = 2,
[Description("Item 3")]
Item3 = 4,
}
public enum MyEnum {
[Description("Item 1")]
Item1,
[Description("Item 2")]
Item2,
[Description("Item 3")]
Item3,
}
To get the attributes I tried:
var a = MyEnumWithFlags.Item1 | MyEnumWithFlags.Item3;
var b = a.GetAttributes<DescriptionAttribute>();
This works fine. Variable b has to attributes: "Item 1" and "Item 2".
Then I tried with Myenum that has no flags:
var c = MyEnum.Item1;
var d = c.GetAttributes<DescriptionAttribute>();
In this case variable d has all the enum attributes. Not only the Item1.
Does anyone knows what might be wrong? The GetAttributes extension is:
public static List<T> GetAttributes<T>(this Enum value) where T : Attribute {
List<T> attributes = new List<T>();
IEnumerable<Enum> flags = Enum.GetValues(value.GetType()).Cast<Enum>().Where(value.HasFlag);
if (flags != null) {
foreach (Enum flag in flags) {
MemberInfo info = flag.GetType().GetMember(flag.ToString()).FirstOrDefault();
if (info != null)
attributes.Add((T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault());
}
return attributes;
}
return null;
}
UPDATE
By checking if the enum is of type flags I end up with the following:
public static List<T> GetAttributes<T>(this Enum value) where T : Attribute {
Type type = value.GetType();
if (type.GetCustomAttributes<FlagsAttribute>().Any()) {
List<T> attributes = new List<T>();
IEnumerable<Enum> flags = Enum.GetValues(type).Cast<Enum>().Where(value.HasFlag);
if (flags != null) {
foreach (Enum flag in flags) {
MemberInfo info = flag.GetType().GetMember(flag.ToString()).FirstOrDefault();
if (info != null)
attributes.Add((T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault());
}
return attributes;
}
} else {
MemberInfo info = type.GetMember(value.ToString()).FirstOrDefault();
if (info != null)
return new List<T> { (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault() };
}
return null;
} // GetAttributes
It seems to work now with Flags Enums and No Flags Enums.
Does anyone thinks that this code could be improved?
Thank You