Home
VB.NET
Enum Examples
This page was last reviewed on Aug 1, 2024.
Dot Net Perls
Enum. An VB.NET 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 and make programs easier to maintain. We use the Enum keyword, and place enums in Select Case and If-statements.
Enum.Parse
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.
Here In Main, 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."
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
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
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.
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
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.
Detail The Enum represents a type of animal, which has options for cats and dogs. We finally call Console.WriteLine.
Console.WriteLine
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
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
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
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.
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
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, Sbyte
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
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
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.
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
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."
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
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.
Enum Flags
Info The VB.NET language supports Or, Xor, and And for bitwise operators. We can set the Flags value in this way.
Next We can test for the existence of a flag with the HasFlag function. One enum value can thus have many values at once.
Tip We specify that an enum is a Flags enum by using an Attribute (named Flags). We surround it with angle brackets.
Attribute
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
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).
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
WEEKEND ENUM VALUE: Saturday WEEKEND ENUM VALUE: Sunday
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 1, 2024 (edit link).
Home
Changes
© 2007-2024 Sam Allen.