Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding out if an enum has the "Flags" attribute set

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,
}
like image 988
Carlo V. Dango Avatar asked Jan 22 '13 14:01

Carlo V. Dango


People also ask

What are flags in enum?

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.

How can you determine if a variable contains an enumeration value?

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.

What is Flag attribute?

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.

How do you check if a property is an enum?

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.


3 Answers

if (typeof(MyEnum).GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
like image 185
SLaks Avatar answered Oct 12 '22 14:10

SLaks


If you are on .NET 4.5:

if (typeof(MyColor).GetCustomAttributes<FlagsAttribute>().Any())
{
}
like image 41
cuongle Avatar answered Oct 12 '22 14:10

cuongle


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.

Example

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
like image 24
khellang Avatar answered Oct 12 '22 13:10

khellang