In Visual Basic, enumerations (Enum) are used to declare named integer constants, which improves code readability and maintainability. Enumerations are declared as follows:
Public Enum StatusCode Success = 0 Warning = 1 Error = 2 End Enum
Important nuances:
Example usage:
Dim code As StatusCode = StatusCode.Success If code = StatusCode.Error Then Console.WriteLine("Error!") End If ' Assigning a non-existent value code = CType(5, StatusCode) ' This will compile, but the value is not defined in Enum
Can you assign a variable of type Enum a value not listed in the Enum? What could this lead to?
Yes, in Visual Basic (and .NET in general), any suitable (by base type) numeric value can be assigned to an Enum variable through explicit conversion (
CType,DirectCast). This will not cause a compilation error, but could lead to potential issues during further use, as such values do not correspond to the names of Enum elements and cannot be correctly parsed through methods such as ToString. For example:
Dim code As StatusCode = CType(42, StatusCode) Console.WriteLine(code) ' will output '42', not the name of the Enum element
Story
In a large project, developers passed statuses as int via WebAPI, and on the client side, they converted them to Enum. When new values that were not added to Enum appeared, the application did not display correct information, as there were no checks for the "validity" of the Enum value.
Story
Using Enum without Option Strict led to random numeric values received from external sources being implicitly converted to Enum, causing bugs in business logic that were difficult to trace at runtime.
Story
The absence of an explicit underlying type for Enum (e.g., Byte for memory saving) led to unexpected integer overflow in a tight microcontroller solution on Compact Framework.