Not all enums are integers. They can be s/bytes, u/shorts, u/ints and u/longs. Converting to an int can cause overflow exceptions, as can converting to an unsigned when a signed value is negative. If you insist on a generic method, this should work:
static ulong ToUInt64<TEnum>(TEnum value) where TEnum : struct, IConvertible
{
// Silently convert the value to UInt64 from the other base
// types for enum without throwing an exception.
// Required because the Convert functions do overflow checks.
TypeCode typeCode = value.GetTypeCode();
ulong result;
switch (typeCode)
{
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
result = (UInt64)value.ToInt64(CultureInfo.InvariantCulture);
break;
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
result = value.ToUInt64(CultureInfo.InvariantCulture);
break;
default:
throw new InvalidOperationException();
}
return result;
}
But really, isn't casting it directly without a generic helper just easier?
long value = (long)Event.Emails;
By the way, you can't do (int)value
in a generic method. It won't compile, perhaps because the compiler doesn't have an enum constraint and doesn't know the enum size at compile time? The generic version must go through the IConvertible interface instead.