HomeSearch

VB.NET Enum Examples

Use Enum values to stores named and magic constants. Use if-statements with enums.
Enum. An Enum type stores special values. These are named constants. With an Enum, we replace magic constants throughout a program.
Enums make code clearer. They organize code. They make code easier to maintain. We use the Enum keyword to specify a new Enum type. We use enums with Select Case and If-statements.
Example. Here we use an Enum named Importance. The Enum represents a constant value. It indicates a value's priority. The names of the constants in an Enum can be any valid identifiers.

Select: In the Main method, we use a Select statement on an enum variable. This enables a fast match for the correct Enum value.

Select Case

Result: The case for Importance.Critical is selected. The output of the program is "True."

VB.NET program that uses Enum with Select Module Module1 ''' <summary> ''' Levels of importance. ''' </summary> Enum Importance None = 0 Trivial = 1 Regular = 2 Important = 3 Critical = 4 End Enum Sub Main() Dim value As Importance = Importance.Critical ' Select the enum and print a value. Select Case value Case Importance.Trivial Console.WriteLine("Not true") Return Case Importance.Critical Console.WriteLine("True") Exit Select End Select End Sub End Module Output True
If, ElseIf. Often we use the If and ElseIf constructs to implement checks for certain Enum values. With conditionals, we check an Enum Dim variable against named constants in an Enum type.If Then

Here: We represent a markup tag, such as HTML, in a conceptual model as an Enum value. We test the tags with the If and ElseIf statements.

VB.NET program that uses enum If and ElseIf Module Module1 ''' <summary> ''' Represents tag type. ''' </summary> Enum TagType None = 0 BoldTag = 1 ItalicsTag = 2 HyperlinkTag = 3 End Enum Sub Main() ' Create enum type variable. Dim value As TagType = TagType.HyperlinkTag ' Use enum in If-statement. ' ... Also use ElseIf statement. If value = TagType.BoldTag Then Console.WriteLine("Bold") ElseIf value = TagType.HyperlinkTag Then Console.WriteLine("Not true") End If End Sub End Module Output Not true
ToString. Suppose we want a string representation. We need to invoke ToString explicitly on an Enum variable when we pass it to the Console.Write or WriteLine subs.

Important: If we do not call ToString, we will receive the numeric value of the enum, not the string representation.

Here: In this example, we show the ToString method on an Enum variable called AnimalType.

Animal: The Enum represents a type of animal, which contains options for cats and dogs. We finally call Console.WriteLine.

Console
VB.NET program that uses ToString, Enum Module Module1 ''' <summary> ''' Type of animal. ''' </summary> Enum AnimalType None = 0 Cat = 1 Dog = 2 End Enum ''' <summary> ''' Type of visibility. ''' </summary> Enum VisibilityType None = 0 Hidden = 2 Visible = 4 End Enum Sub Main() Dim dog As AnimalType = AnimalType.Dog Dim hidden As VisibilityType = VisibilityType.Hidden ' Write to the Console with the ToString method. Console.WriteLine(dog.ToString) Console.WriteLine(hidden.ToString) End Sub End Module Output Dog Hidden
Stack. Here we use a Stack to represent a markup tree. If we have an HTML document with tags, we could use a Stack of Enum values (TagType) to represent this tree.

Note: You could use this functionality for HTML validation as well. Opening and closing tags could be matched.

Tip: To use the Stack collection, we typically use the Push, Pop as well as Peek methods.

Stack
VB.NET program that uses Stack, Enum Module Module1 Enum TagType None = 0 BoldTag = 1 ItalicsTag = 2 HyperlinkTag = 3 End Enum Sub Main() ' Create a new Stack generic instance. Dim stack As New Stack(Of TagType) ' Add a BoldTag to it. stack.Push(TagType.BoldTag) ' Add an ItalicsTag to it. stack.Push(TagType.ItalicsTag) ' Pop the top element. ' ... Then write it to the Console. Dim popped As TagType = stack.Pop() Console.WriteLine(popped) Console.WriteLine(popped.ToString) End Sub End Module Output 2 ItalicsTag
Default. An Enum has a default value. This corresponds to the value that equals 0 within the Enum type, which is by default the first listed one.

Note: The default values of an enum proceed up from 0. So the first is zero, the second is one, and the third is two.

Also: When part of a class, an Enum does not need initialization to this default value. Initializing it to zero is a performance negative.

VB.NET program that uses Enum, default value Module Module1 Enum Level Normal Low High End Enum Class Item ''' <summary> ''' Public enum. ''' </summary> Public _level As Level End Class Sub Main() ' The default value for an enum is the one equal to 0. Dim v As Item = New Item Console.WriteLine(v._level.ToString()) End Sub End Module Output Normal
Types. Enums have a backing type—a data representation like Integer or Byte. By default, Enums are represented as Integers. But we can, with the "As" keyword change this.

Here: We create a Byte Enum with the "as Byte" keywords. Each instance of "Code" will only require one byte.

Byte

Tip: This ability is useful when designing a Class that is instantiated many times in memory.

Tip 2: With smaller types, we can reduce memory usage. Four Bytes are packed into the size occupied by one Integer.

Integer
VB.NET program that uses enum backing type, byte Module Module1 Enum Code As Byte Small = 0 Medium = 1 Large = 2 End Enum Sub Main() ' The value is represented in a byte. Dim value As Code = Code.Medium Console.WriteLine(value) End Sub End Module Output 1
Other values. In VB.NET we can specify an enum variable has a value that is not in the enum. No warning or error is issued. So enums help with, but do not enforce, correct code.
VB.NET program that uses other values in enum Module Module1 Enum PageColor None = 0 Red = 1 Blue = 2 Green = 3 End Enum Sub Main() ' This value does not exist in the enum type. Dim value As PageColor = 4 ' We can still test an enum against any value. If value = 4 Then Console.WriteLine("Value is 4") End If End Sub End Module Output Value is 4
Enum argument. We can pass an enum as an argument to a Sub or Function. We specify the enum name as the type—here we use the name "Position."
VB.NET program that uses enum as argument to Sub Module Module1 Enum Position Above Below End Enum Sub Main() ' Pass enum to function. TestValue(Position.Below) End Sub Sub TestValue(ByVal value As Position) ' Test enum argument. If value = Position.Below Then Console.WriteLine("POSITION IS BELOW") End If End Sub End Module Output POSITION IS BELOW
Enum Flags. We can use the Flags attribute on an Enum to enable some bitwise operations. With a Flags enum, we can use the numbers 0, 1, 2 and further to indicate values.

Bitwise Or: The VB.NET language supports Or, Xor, and And for bitwise operators. We can set the Flags value in this way.

Bitwise Operators: Microsoft Docs

HasFlag: We can test for the existence of a flag with the HasFlag function. One enum value can thus have many values at once.

Attribute: We specify that an enum is a Flags enum by using an Attribute (named Flags). We surround it with angle brackets.

Attribute
VB.NET program that uses Enum Flags Module Module1 <Flags> Enum FlagData None = 0 Cached = 1 Current = 2 Obsolete = 4 End Enum Sub Main() ' The or operator supports bitwise operations. ' ... This is the same as 1 | 2. Dim attr As FlagData = FlagData.Cached Or FlagData.Current ' Check for flag existence. If attr.HasFlag(FlagData.Cached) Then Console.WriteLine("File is cached") End If If attr.HasFlag(FlagData.Current) Then Console.WriteLine("File is current") End If If attr.HasFlag(FlagData.Obsolete) Then Console.WriteLine("Not reached") End If End Sub End Module Output File is cached File is current
DayOfWeek, enum. Some enums are built into the .NET Framework—we can reuse them in our programs. The DayOfWeek enum stores all 7 days of the week.

So: If we wish to represent a day in a class or collection, we can use the DayOfWeek enum (it works just like any other enum).

VB.NET program that uses DayOfWeek enum Module Module1 Sub Main() ' Add weekend day enums to list. Dim list = New List(Of DayOfWeek)() list.Add(DayOfWeek.Saturday) list.Add(DayOfWeek.Sunday) ' Loop over enums in list. For Each value As DayOfWeek In list Console.WriteLine("WEEKEND ENUM VALUE: {0}", value) Next End Sub End Module Output WEEKEND ENUM VALUE: Saturday WEEKEND ENUM VALUE: Sunday
Parse. If we have a String value that contains an Enum name, how can we convert it to an Enum value? The Enum.Parse and Enum.TryParse functions are available for this purpose.Enum.Parse, TryParse
A summary. Enums are used to represent a set of named constants. Typically, these named, symbolic constants are a selection of options for a specific variable.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls