MSDN Documentation

Enums in VB.NET

Enumerations (or enums) are a data type that consists of a set of named constants. They provide a convenient way to define a set of discrete values, making your code more readable and maintainable. Instead of using magic numbers or strings, you can use descriptive enum members.

What is an Enum?

An enum is declared using the Enum keyword. Each member of the enum is assigned an underlying integral value, starting from 0 by default if not explicitly specified. You can also explicitly assign values to enum members.

Declaring an Enum

Here's how you declare a simple enum for days of the week:

Public Enum DaysOfWeek
    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
End Enum

In this example, Sunday is implicitly assigned the value 0, Monday is 1, and so on.

Explicitly Assigning Values

You can assign specific integral values to enum members:

Public Enum ErrorCodes
    Success = 0
    FileNotFound = 101
    AccessDenied = 403
    InternalServerError = 500
End Enum

Using Enums

Once an enum is declared, you can use it to declare variables and assign values to them:

Dim today As DaysOfWeek = DaysOfWeek.Wednesday
Dim errorCode As ErrorCodes = ErrorCodes.FileNotFound

' You can also compare enum values
If today = DaysOfWeek.Wednesday Then
    Console.WriteLine("It's Wednesday!")
End If

Accessing Underlying Values

You can explicitly cast an enum member to its underlying integral type:

Dim dayValue As Integer = CInt(DaysOfWeek.Friday) ' dayValue will be 5
Dim errorCodeValue As Integer = CInt(ErrorCodes.AccessDenied) ' errorCodeValue will be 403

Conversely, you can convert an integral value to an enum member:

Dim day As DaysOfWeek = CType(2, DaysOfWeek) ' day will be DaysOfWeek.Tuesday

The Enum Statement

The Enum statement is a member-level statement that can only be declared within a module, class, or structure, but not within a procedure.

Attributes

Enums support attributes. For example, the [Flags] attribute is useful for creating enums that can be combined using bitwise operations. This is common for settings or permissions.

Imports System

<Flags()>
Public Enum FilePermissions
    None = 0
    Read = 1
    Write = 2
    Execute = 4
    All = Read Or Write Or Execute
End Enum

' Example usage:
Dim userPermissions As FilePermissions = FilePermissions.Read Or FilePermissions.Write

If userPermissions.HasFlag(FilePermissions.Read) Then
    Console.WriteLine("User has read permission.")
End If

If userPermissions = FilePermissions.All Then
    Console.WriteLine("User has all permissions.")
ElseIf userPermissions = (FilePermissions.Read Or FilePermissions.Write) Then
    Console.WriteLine("User has read and write permissions.")
End If

Note on Flags Attribute

When using the [Flags] attribute, it's a convention to use powers of 2 for the enum values (1, 2, 4, 8, etc.) and to include a None = 0 member. This allows for effective bitwise combination and checking.

Benefits of Using Enums

Tip

When choosing the underlying type for an enum, consider the range of values your enum members will represent. For instance, if you have many enum members or large assigned values, using Long might be more appropriate than Integer.

Common Enum Scenarios

Example: Managing Application Settings

Consider an enum for different application themes:

Public Enum AppTheme
    Light
    Dark
    HighContrast
End Enum

Public Class ApplicationManager
    Private currentTheme As AppTheme

    Public Sub SetTheme(theme As AppTheme)
        currentTheme = theme
        ' Code to apply the theme to the UI...
        Console.WriteLine($"Theme set to: {currentTheme.ToString()}")
    End Sub

    Public Function GetTheme() As AppTheme
        Return currentTheme
    End Function
End Class

' Usage:
Dim manager As New ApplicationManager()
manager.SetTheme(AppTheme.Dark)
Dim activeTheme As AppTheme = manager.GetTheme() ' activeTheme is AppTheme.Dark

Enums are a fundamental part of object-oriented programming in VB.NET, contributing significantly to robust and understandable code.