ProgrammingVB.NET Developer, WinForms Developer

How are enumerations (Enum) implemented and processed in Visual Basic? What nuances exist when assigning and comparing Enum values, and can type conversion errors occur?

Pass interviews with Hintsage AI assistant

Answer

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:

  • Underlying type size: By default, Enum is based on the Integer type, but a different size (e.g., Byte) can be explicitly specified.
  • Type conversion: Assigning a numeric value not defined in Enum is permitted but may lead to logical errors — such values are not considered "valid" enumeration elements.
  • Comparison: Comparisons use the integer value of Enum. Implicit type conversion is possible, so extraneous numeric values can potentially pass the check.
  • Strict typing: With Option Strict On, implicit conversion from numeric types to Enum and vice versa is not allowed.

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

Trick question

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

Examples of real errors due to ignorance of the nuances of the topic


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.