Enum.Parse
Sometimes a String
must be converted into an Enum
. This requires a special Function call. In VB.NET we use the Enum.Parse
, or TryParse
, Functions.
We handle exceptions and errors for each method. Often TryParse
is a better choice if our data is not already validated.
This example introduces an Enum
of name PetType
. In the Main
Sub
, we have a String
literal with value "Dog". We call [Enum
].Parse to get its same-named Enum
.
GetType
Function is used with the argument VehicleType
. This is the Type argument to the Enum.Parse
Function.Enum
type uses a special syntax where it is surrounded by square brackets. This indicates a Type, not the Enum
keyword.Module Module1 ''' <summary> ''' Types of pets. ''' </summary> Enum PetType None Cat Dog End Enum Sub Main() ' Convert String to Enum. Dim value As String = "Dog" Dim type As PetType = [Enum].Parse(GetType(PetType), value) ' Test Enum. If type = PetType.Dog Then Console.WriteLine("Equals dog") End If End Sub End ModuleEquals dog
Next, we learn that Enum.Parse
will throw an Exception
on an invalid String
. One way to handle this problem is to use a Try-Catch block to capture possible errors.
Module Module1 Enum VehicleType None Truck Sedan Coupe End Enum Sub Main() ' An invalid String. Dim value As String = "Spaceship" Try ' Parse the invalid String. Dim type As VehicleType = [Enum].Parse(GetType(VehicleType), value) Catch ex As Exception ' Write the Exception. Console.WriteLine(ex) End Try End Sub End ModuleSystem.ArgumentException: Requested value 'Spaceship' was not found. at System.Enum.EnumResult.SetFailure...
TryParse
Next, the TryParse
Function is available. It handles errors in a safer, faster way. It does not throw an Exception
on an invalid String
that cannot be converted.
Enum.TryParse
returns False if the string
cannot be converted. The Enum
is set to the default value.Module Module1 Enum VehicleType None Truck Sedan End Enum Sub Main() ' An invalid String. Dim value As String = "Starship" ' Parse the invalid String. Dim result As VehicleType [Enum].TryParse(value, result) ' It is the default. Console.WriteLine(result.ToString()) End Sub End ModuleNone
We require no custom conversion methods to parse Enums in VB.NET programs. Instead, the Enum.Parse
and TryParse
Functions fill this need.
If an invalid String
may be encountered, the TryParse
Function is often superior. Avoiding exceptions is faster in most programs.