Checking Enum Flags

If you using an enum that uses bit flags, here is an easy way to check to see if one or more if the values are set.

VB

Public Shared Function CheckFlags(value As [Enum], flags As [Enum]) As Boolean
    If [Enum].GetUnderlyingType(value.[GetType]()) = GetType(ULong) Then
        Return (Convert.ToUInt64(value) And Convert.ToUInt64(flags)) <> 0
    Else
        Return (Convert.ToInt64(value) And Convert.ToInt64(flags)) <> 0
    End If
End Function

C#

public static bool CheckFlags(Enum value, Enum flags)
{
    if (Enum.GetUnderlyingType(value.GetType()) == typeof(ulong)) {
        return (Convert.ToUInt64(value) & Convert.ToUInt64(flags)) != 0;
    }
    else {
        return (Convert.ToInt64(value) & Convert.ToInt64(flags)) != 0;
    }
}

Usage

CheckFlags(value, EnumModes.Save | EnumModes.Store)

Tip By: David McCarter


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.