Florian Koch Florian Koch - 1 year ago 67
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

. The reason why I want this is that
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 (
) 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 Source

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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download