Showing posts with label Parse. Show all posts
Showing posts with label Parse. Show all posts

Wednesday, September 21, 2016

String to Enum parsing


The normal way of parsing an string containing an enum value:

var text = "Unknown";
var parsed = (KnownType)Enum.Parse(typeof(KnownType), text, true);

I've always found this to be ugly when scattered in the code base and usually I solve it by adding the following string extension to the projects utility class:

public static <T> ParseEnum(this string s)
{
    return (T) Enum.Parse(typeof (T), s, true);
}

Usage:

var text = "Unknown";
var parsed = text.ParseEnum<KnownType>();


Hope this helps someone out there