Introduction
I had a situation come up where I needed to test whether a given value in a database fell inside the range of values given by an enumeration. After fussing around with several ways of testing this, I found a simple, elegant solution that seemed worth documenting.
The theory
In the .NET Framework, enumerations are handled by the Enum
class. When you have a code such as
public enum SecurityLevel
{
Undefined = -1,
Guest = 0,
Assistant = 1,
Representative = 2,
Employee = 3,
Executive = 5,
Administrator = 8
}
VB.NET
Public Enum SecurityLevelEnum
Undefined = -1
Guest = 0
Assistant = 1
Representative = 2
Employee = 3
Executive = 5
Administrator = 8
End Enum
the Framework actually creates an instance of Enum
and populates it with your values. And like any class, Enum
has methods that can be invoked.
The practice
Of interest is the Shared
(static
in C#) method GetValues
, which takes the contents of an enumeration type and returns it as an instance of the System.Array
class. If we take this result and convert it to an IEnumerable
of a given type, we can use the LINQ extentions to get some useful information about the enumeration.
if ( ((int[]) Enum.GetValues(typeof(SecurityLevel))).Contains(7) )
...
if ( 3 >= ((int[]) Enum.GetValues(typeof(SecurityLevel))).Min() )
...
if ( 6 < ((int[]) Enum.GetValues(typeof(SecurityLevel))).Max() )
VB.NET
If CType([Enum].GetValues(SecurityLevel), Integer()).Contains(7) Then
...
If 3 >= CType([Enum].GetValues(SecurityLevel), Integer()).Min() Then
...
If 6 < CType([Enum].GetValues(SecurityLevel), Integer()).Max() Then
Note that because Enum
is a keyword in VB.NET, using it as a class requires that you use square brackets.
The first example will return False
, because the given enumeration does not contain a value that corresponds to the integer value 7. The second and third tests return True
.
You can generalize this as a function which will work for any integer-based enumeration:
bool EnumHasValue(Type Typ, int Value)
{
return ((int[])Enum.GetValues(Typ)).Contains(Value);
}
...
if (EnumHasValue(typeof(SecurityLevel), 7)
VB.NET
Function EnumHasValue(ByVal Typ As Type, ByVal Value As Integer) As Boolean
Return CType([Enum].GetValues(Typ), Integer()).Contains(Value)
End Function
...
If EnumHasValue(GetType(SecurityLevel), 7) Then
Of course, enumerations do not have to be integer-based: you can convert the result of GetValues
into an array of strings, doubles, whatever you can turn into an enumeration.
If your experimentation comes up with something interesting, please post your results as a comment.