Using reflection, how do I determine whether an enum has the Flags attribute or not
so for MyColor return true
[Flags]
public enum MyColor
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
and for MyTrade return false
public enum MyTrade
{
Stock = 1,
Floor = 2,
Net = 4,
}
Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.
Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not.
A Flags is an attribute that allows us to represent an enum as a collection of values rather than a single value. So, let's see how we can implement the Flags attribute on enumeration: [Flags] public enum UserType.
In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false. It is a read-only property.
if (typeof(MyEnum).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
If you are on .NET 4.5:
if (typeof(MyColor).GetCustomAttributes<FlagsAttribute>().Any())
{
}
If you just want to check if an attribute is present, without inspecting any attribute data, you should use MemberInfo.IsDefined
. It returns a bool
that indicates "whether one or more attributes of the specified type or of its derived types is applied to this member" instead of dealing with a collection of attributes.
typeof(MyColor).IsDefined(typeof(FlagsAttribute), inherit: false); // true
typeof(MyTrade).IsDefined(typeof(FlagsAttribute), inherit: false); // false
Or, if you're on .NET 4.5+:
using System.Reflection;
typeof(MyColor).IsDefined<FlagsAttribute>(inherit: false); // true
typeof(MyTrade).IsDefined<FlagsAttribute>(inherit: false); // false
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