HomeSearch

VB.NET Enum.Parse, TryParse: Convert String to Enum

Use the Enum.Parse and Enum.TryParse Functions to convert Strings to Enum values.
Enum.Parse, TryParse. 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.Enum
Example. This example introduces an Enum of name VehicleType. This Enum contains different kinds of vehicles. In the Main Sub, we have a String literal with value "Truck". We call [Enum].Parse to get its same-named Enum.

GetType: The GetType Function is used with the argument VehicleType. This is the Type argument to the Enum.Parse Function.

Brackets: The Enum type uses a special syntax where it is surrounded by square brackets. This indicates a Type, not the Enum keyword.

VB.NET program that uses Enum.Parse Module Module1 ''' <summary> ''' Types of vehicles. ''' </summary> Enum VehicleType None Truck Sedan Coupe End Enum Sub Main() ' Convert String to Enum. Dim value As String = "Truck" Dim type As VehicleType = [Enum].Parse(GetType(VehicleType), value) ' Test Enum. If type = VehicleType.Truck Then Console.WriteLine("Equals truck") End If End Sub End Module Output Equals truck
Example 2. Next, we learn that Enum.Parse will throw an Exception on an invalid String. This is problematic. One way to handle this problem is to use a Try-Catch block to capture possible errors. Please also see the TryParse Function.
VB.NET program that handles Parse, Exception 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 Module Output System.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. Instead, it returns False. The Enum is set to the default value.
VB.NET program that uses TryParse 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 Module Output None
Summary. 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.