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.

Leave a Comment