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?