If you want the numeric value, you can use Convert.ToInt32(selectedItem)
and then do a ToString()
on it. This if the enum
is based on an int
. (technically it will work unless there is a value of the enum
that is too much big for the int
)
And now, thanks to the magic of Expression trees... Two classes:
public static class EnumToString<T>
{
public static readonly Func<T, string> Do;
static EnumToString()
{
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException();
}
Type baseType = type.GetEnumUnderlyingType();
var par1 = Expression.Parameter(typeof(T));
var cast = Expression.Convert(par1, baseType);
Expression<Func<object, string>> toString = p => p.ToString();
var body = (MethodCallExpression)toString.Body;
var toString2 = Expression.Call(cast, body.Method);
Do = Expression.Lambda<Func<T, string>>(toString2, par1).Compile();
}
}
public static class EnumToObject<T>
{
public static readonly Func<T, object> Do;
static EnumToObject()
{
Type type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException();
}
Type baseType = type.GetEnumUnderlyingType();
var par1 = Expression.Parameter(typeof(T));
var cast1 = Expression.Convert(par1, baseType);
var cast2 = Expression.Convert(cast1, typeof(object));
Do = Expression.Lambda<Func<T, object>>(cast2, par1).Compile();
}
}
static void Main()
{
string str = EnumToString<MyEnum>.Do(MyEnum.Foo); // "1"
object obj = EnumToObject<MyEnum>.Do(MyEnum.Foo); // (int)1
}
The first one, EnumToString<>
takes the value of an enum value and convert it to string. The second one converts the value of an enum value to its base type (whatever it's) and returns an object
(so it boxes the base value) (on which you can do a .ToString()
, for example).
To use them you would have to change your class to something like:
IEnumerable<SelectListItem> GetAllEnumValues<T>()
{
// In truth, the array returned by Enum.GetValues **is** strongly typed
// but is "downcasted" to Array. So we re-upcast it.
T[] values = (T[])Enum.GetValues(typeof(T));
...
Value = EnumToString<T>.Do(selectedItem),
// or
Value = EnumToObject<T>.Do(selectedItem).ToString(),
}
But note that all of this is nearly useless, because there is the special formatter d
:
MyEnum enu = MyEnum.Something; // (where MyEnum.Something == 1)
string str = enu.ToString("d"); // 1
Enum enu2 = enu;
string str2 = enu2.ToString("d"); // 1
See Enumeration Format Strings