Florian Koch Florian Koch - 1 month ago 9
C# Question

Cast generic but known to be enum nullable type to nullable int

I know this may sound a bit weird, but I want to cast an object of

T?
to
int?
. The reason why I want this is that
T
is always an enum and I also know this enum will be castable to int. I'm creating a generic wrapper class for enums and found this "solution" to constrain the generic type to be an enum type.

My code currently looks like this:

public class EnumWrapper<T>
where T : struct, IConvertible
{
public EnumWrapper()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
}

public T? Enum { get; set; }

public int? EnumValue => (int?)Enum; // this won't compile

...
}


I know that casting to object before casting to a value type (
(int?)(object)Enum
) tricks the compiler, but does this work here too? I suspect the nullable interferes with this.

So my question is: What is the best way to implement this generic behavior?

Answer

Since T is IConvertible, you can avoid casting and boxing using the ToInt32() method:

public int? EnumValue => this.Enum?.ToInt32(CultureInfo.CurrentCulture.NumberFormat);

And this.Enum? will make sure to return null in case the actual value is missing.

See MSDN