Say I have an enum,
public enum Colours
{
Red,
Blue
}
The only way I can see of parsing them is doing something like:
If I'm parsing a "trusted" enum, then I use Enum.Parse().
By "trusted" I mean, I know it will ALWAYS be a valid enum without ever erroring... ever!
But there are times when "you never know what you're gonna get", and for those times, you need to use a nullable return value. Since .net doesn't offer this baked in, you can roll your own. Here's my recipe:
public static TEnum? ParseEnum(string sEnumValue) where TEnum : struct
{
TEnum eTemp;
TEnum? eReturn = null;
if (Enum.TryParse(sEnumValue, out eTemp) == true)
eReturn = eTemp;
return eReturn;
}
To use this method, call it like so:
eColor? SelectedColor = ParseEnum("Red");
Just add this method to a class you use to store your other commonly used utility functions.