Can I cast from a generic type to an enum in C#?
27,352
Solution 1
Like this:
return (T)(object)value;
Solution 2
Change this:
Enum value = (Enum)Enum.ToObject(enumType, enumAsInt);
to this:
T value = (T)Enum.ToObject(enumType, enumAsInt);
and remove the cast :)
Solution 3
For information, using the generic constraint Enum
is available from C# 7.3 and greater.
Related videos on Youtube
Comments
-
Justin almost 4 years
I'm writing an utility function that gets a integer from the database and returns a typed enum to the application.
Here is what I tried to do (note I pass in a data reader and column name instead of the
int
in my real function):public static T GetEnum<T>(int enumAsInt) { Type enumType = typeof(T); Enum value = (Enum)Enum.ToObject(enumType, enumAsInt); if (Enum.IsDefined(enumType, value) == false) { throw new NotSupportedException("Unable to convert value from database to the type: " + enumType.ToString()); } return (T)value; }
But it won't let me cast
(T)value
saying:Cannot convert type 'System.Enum' to 'T'.
Also I've read quite a bit of mixed reviews about using
Enum.IsDefined
. Performance wise it sounds very poor. How else can I guarantee a valid value?-
nawfal almost 11 yearsNote that if the case had been other way around, say, you have to do
(Enum)value
and you getCannot convert type 'T' to 'System.Enum'
, you could merely do anas
cast, likevalue as Enum
. -
keithl8041 about 10 yearsNot true (at least in my case), you get the old 'The as operator must be used with a reference or nullable type ('Foo.bar' is a non-nullable value type) error.
-
-
João Angelo almost 14 yearsIt would be better to initially declare
value
as anobject
. -
Justin almost 14 yearsThanks that seems to compile. I don't understand the reason for the error then? Bonus points if you can explain why in the interest of learning:)
-
SLaks almost 14 yearsThe compiler doesn't realize that
T
is a enum type. As far as it is aware,T
might beDateTime
. Therefore, you cannot cast directly from any type other thanobject
toT
. -
Justin almost 14 yearsI did try to constrain T in the method signature with "where T : Enum". But the compiler tells me Constraint cannot be special class 'System.Enum'.
-
SLaks almost 14 years
-
AgentFire about 9 yearsCan't this be done without box-unbox? May be using this
__makeref
thing -
Tod Cunningham over 5 yearsI couldn't get Slaks solution to work, but using the Enum.ToObject cast worked great.