Background
Enums in Visual Basic are used to improve the readability and reliability of code. An Enum allows the definition of a set of named constants, creating a strict set of permissible values for program logic.
The Problem
Many believe that Enums completely restrict the values of a variable to one of the enumerated members. However, in reality, an Enum variable stores an integer type value, and any valid value for the underlying type can be assigned to it, which can lead to errors and unexpected behavior.
Solution
In VB.NET, it is not prohibited to assign a value to an Enum variable that is not defined in the list. To safely iterate through the values, the System.Enum.GetValues function is used. Validity checks are performed through additional checks.
Example code:
Enum Colors Red = 1 Green = 2 Blue = 3 End Enum Dim c As Colors = CType(4, Colors) ' This will not be a compilation error! For Each value As Colors In [Enum].GetValues(GetType(Colors)) Console.WriteLine(value) Next ' Validation If [Enum].IsDefined(GetType(Colors), c) Then Console.WriteLine("OK") Else Console.WriteLine("Invalid value!") End If
Key Features:
Can it be guaranteed that an Enum variable always contains only declared values?
No. At the language level, Enum is a lightweight wrapper around the underlying numeric type. Checking the validity of specific values must always be done explicitly through IsDefined.
Is it possible to get the string representation of an Enum from its value, even if it is not declared?
Yes. The ToString method for an Enum assigned a non-existent value will yield this numeric equivalent as a string: for example, for Colors = 4, the result will be "4".
What happens if all values are enumerated through Enum.GetValues, and then a number outside the enumeration is assigned to an Enum variable?
Iterating with GetValues will only return declared members, but the Enum variable can still contain any number outside the range — this will be a logical error, not a syntax error.
Input from the screen is directly converted into Enum without validation — resulting in incorrect values and application failure at later stages.
Pros:
Cons:
User input values are first validated through Enum.IsDefined, ensuring correct handling even for invalid data.
Pros:
Cons: