C# Casting with objects to Enums

Something like this probably will help you:

public T dosomething<T>(object o)
{
   T enumVal= (T)Enum.Parse(typeof(T), o.ToString());
   return enumVal;
}

But this will work only with enums, for clear reason of using Enum.Parse(..)

And use this like, for example:

object o = 4;
dosomething<Crustaceans>(o);

That will return Toad in your case.


There are cases when you can not use Generics (like in a WPF Converter when you get the value as an object). In this case you can not cast to int because the enum type may not be an int. This is a general way to do it without Generics. The Example is given inside a WPF Converter, but the code inside is general:

using System;
using System.Windows;
using System.Windows.Data;

.
.
.

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    var enumType = value.GetType();
    var underlyingType = Enum.GetUnderlyingType(enumType);
    var numericValue = System.Convert.ChangeType(value, underlyingType);
    return numericValue;
}

In case of integral types boxed as objects the correct way to do the conversion is using Enum.ToObject method:

public T Convert<T>(object o)
{
   T enumVal= (T)Enum.ToObject(typeof(T), o);
   return enumVal;
}

Tags:

C#

Enums

C# 4.0