Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt()
, ToString()
The other way around would be possibly... the other way around ;) Extend int and string with generic extension methods which will take as type parameter the type of an enum:
public static TEnum ToEnum(this int val)
{
return (TEnum) System.Enum.ToObject(typeof(TEnum), val);
}
public static TEnum ToEnum(this string val)
{
return (TEnum) System.Enum.Parse(typeof(TEnum), val);
}
Usage:
var redFromInt = 141.ToEnum();
var redFromString = "Red".ToEnum();
There is unfortunately no generic constraint for Enums, so we have to check TEnum type during runtime; to simplify we'll leave that verification to Enum.ToObject
and Enum.Parse
methods.