sweetfa sweetfa - 1 month ago 13
C# Question

C# Casting with objects to Enums

This question relates to casting of enums within generic methods

Given an enum

public enum Crustaceans
{
Frog = 1,
Toad = 4
}


I can create an instance of my enum simply enough

short val = 4;
Crustaceans crusty = (Crustaceans) val;


However, if

short val = 4;
object obj = (object) val;
Crustaceans crusty = (Crustaceans)obj;


a runtime exception is thrown attempting to perform the initialisation of crusty.

Can anyone explain why this is happening, and why it is not legal to do such a thing.

Not that I really wanted to do this, but I cam across an issue when trying to get something similar happening with generics and effectively that is what is happening under the covers. i.e.

public T dosomething<T>(short val) where T : new()
{
T result = (T)(object) val;
return result;
}


So what I am attempting to do is have a generic function that works with enums and non-enums (not so critical-but would be nice) that can be set to a short value without throwing an exception and actually initialising the correct enum value.

Answer

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.

Comments