I would like to cast an int value as nullable enum used a generic function. I thought it would be easy, especially with all the with all the SO about the enum / int casting. The closest question I've found is this one, but unfortunately, it doesn't handle the nullable enums. This question solve the Nullable enums casting question but not with the generic.
Here's a simplified example of what I'm trying to do:
public enum SouthParkCharacters
{
Stan = 0,
Kyle = 1,
Eric = 2,
Kenny = 3
}
public static T CastNullableEnum<T>(int value)
{
return (T)(object)((int?)value).Value;
}
public static T SomeFunction<T>(this int anyEnumValue)
{
SouthParkCharacters? spc = SouthParkCharacters.Kenny;
spc = CastNullableEnum<SouthParkCharacters>(3); //I am working!
spc = CastNullableEnum<SouthParkCharacters?>(3); //Raise error Specified cast is not valid.
//This function will be public so I won't have control over the T
T finalValue = CastNullableEnum<T>(anyEnumValue); //Raise error Specified cast is not valid.
return finalValue;
}
As you can see in last function, a cast for a non-nullable enum is working. The problem is that I want to be able to call the CastNullableEnum from an other generic function, which could use a nullable enum as a generic type.
I know you can pass a generic type as a nullable generic CastNullableEnum<T?>
but can we do the opposite (i.e. pass the nullable underlying type to generic function)?
If this can't be done, then I guess the solution would be to find the right way to cast an enum value in the CastNullableEnum function.