Tuesday, April 28, 2009

Generic enum parsing

Saving an enum value to a string (say for XML persistence) and reading it back in you are forced to write code like the following:
Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);

Now this has always bothered me. I don't know whether it's the return Cast or passing in the object type but the whole syntax seems clunky. So given my new found love of generics I thought there had to be a better way. So I created the following method:

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

Now I can write the following:

Colors colorValue = ParseUtils.ParseEnum<Colors>(colorString);
Seems a lot cleaner.

No comments: