Wednesday, July 28, 2010

Converting string value of an Enum entry to a valid instance of the Enum

"How do I convert a string value of an Enum entry to a valid instance of the Enum?"

C#

String [VariableName] = "StringValue";

[EnumType] [VariableName1] = ([EnumType])Enum.Parse(typeof([EnumType]),[VariableName]);

Example:

String ListSortDirectionString = "Ascending";

System.ComponentModel.ListSortDirection ListSortDirectionEnum = (System.ComponentModel.ListSortDirection)Enum.Parse(typeof(System.ComponentModel.ListSortDirection), ListSortDirectionString);

VB.NET (Option explicit ON, Option strict ON)

DIM [VariableName] AS String = "StringValue";

DIM [VariableName1] AS [EnumType] = CType(Enum.Parse(GetType([EnumType]), [VariableName], True), [EnumType])

Example:

Dim ListSortDirectionString As String = "Ascending"

Dim ListSortDirectionEnum As System.ComponentModel.ListSortDirection = CType([Enum].Parse(GetType(System.ComponentModel.ListSortDirection), ListSortDirectionString, True), System.ComponentModel.ListSortDirection)