Tuesday, August 26, 2008

How to Determine If an Enumeration Is a Bit Field

In .NET you can tell the compiler to treat an enumeration as a bit field by adding a Flags attribute to its declaration. For more information about bit fields in .NET see http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspxhttps://docs.microsoft.com/en-us/dotnet/api/system.flagsattribute. The following function will tell you if an enumeration value is a bit (or flag) field.

Function IsFlagEnum(ByVal value As [Enum]) As Boolean

    If value.GetType().IsDefined( _
GetType(FlagsAttribute), True) = True Then
        Return True
        Return False
    End If


For example, given the following definitions:

<Flags()> _
Public Enum FlagEnum
    None = 0
    ValueA = 1
    ValueB = 2
    ValueC = 4
End Enum

Enum RegularEnum
    Invalid = 0
    ValueA = 1
    ValueB = 2
    ValueC = 3
End Enum

IsFlagEnum(FlagEnum.ValueB) will return True, but IsFlagEnum(RegularEnum.ValueB) will return False.