Quick Tip: Converting an Enum from a string using C# Generics

Here’s a quick tip for you. Converting a string back to an Enum using Generics in C#.

private static T ToEnum<T>(string value)
{
	return (T) Enum.Parse(typeof(T), value);
}

Nice and easy, here’s an example usage – very lame I know.

// Original enum
UriFormat uriFormat = UriFormat.SafeUnescaped;
// Persisted value
string uriFormatText = uriFormat.ToString();
// Back to the enum from the persisted value
UriFormat uriFormatParsed = ToEnum<UriFormat>(uriFormatText);

Console.WriteLine(uriFormat);
Console.WriteLine(uriFormatText);
Console.WriteLine(uriFormatParsed);

Noice?

Related Articles

Comments have been disabled.