In VB.NET, even with Option Strict
on, it\'s possible to pass an Enum around as an Integer.
In my particular situation, someone\'s using an enum similar to
Although .NET 4.0 introduced the Enum.TryParse
method you should not use it for this specific scenario. In .NET an enumeration has an underlying type which can be any of the following (byte
, sbyte
, short
, ushort
, int
, uint
, long
, or ulong
). By default is int
, so any value that is a valid int
is also a valid enumeration value.
This means that Enum.TryParse
reports success even though -1
is not associated to any specified enumeration value.
As other have noted, for this scenarios, you must use Enum.IsDefined
method.
Sample code (in C#):
enum Test { Zero, One, Two }
static void Main(string[] args)
{
Test value;
bool tryParseResult = Enum.TryParse("-1", out value);
bool isDefinedResult = Enum.IsDefined(typeof(Test), -1);
Console.WriteLine("TryParse: {0}", tryParseResult); // True
Console.WriteLine("IsDefined: {0}", isDefinedResult); // False
}