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 this:
Public Enum Animals Monkey = 1 Giraffe = 2 Leopard = 3 Elephant = 4 End Enum
But they are passing it around as an Integer so they can set a value of -1 to be "No animal" (without having to include "No animal" in the Enum itself), i.e.:
Public Sub MakeAnimalJump(animalType As Int32) If animalType < 1 Then ' Clearly not an animal... Else ' Make that animal jump... End If End Sub
However, later on, they're asking for it to be an Animals type again. My question is, aside from a) changing the Enum to include a "None" value or b) cycling through each value in the Enum using [Enum].GetValues(...)
, is there an easy way to work out whether a given Integer maps to a value in the enum or not?
I was hoping there might be an [Enum].TryParse or something, but it doesn't look like there is.
EDIT: As some of you have suggested, there is an Enum.TryParse in .NET 4. Unfortunately, the project in question must still support Windows Server 2000, so we can't use the latest .NET Framework (hopefully we'll be able to drop support for Windows Server 2000 soon..!).
To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.
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<Animal>("-1", out result)
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<Test>("-1", out value); bool isDefinedResult = Enum.IsDefined(typeof(Test), -1); Console.WriteLine("TryParse: {0}", tryParseResult); // True Console.WriteLine("IsDefined: {0}", isDefinedResult); // False }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With