Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't cast an `Enum` value to `int` in a generic method

Tags:

c#

enums

generics

If I have an enum...

public enum Frequency {
  OneOff = 0,
  Monthly = 1,
  Quarterly = 2,
  Annually = 3
}

...then I can do something like this...

int n = (int)Frequency.Annually; 

Given that since C# 7.3, we are able to use Enum as a generic constraint, I expected to be able to do this...

public void Stuff<T>(T val) where T : Enum {
  int v = (int)val;
}

...but the compiler complains, saying it can't convert type T to int.

Anyone able to explain this to me? The generic constraint tells the compiler that T is an enum, and (unless you specifically do it differently) an enum value can be cast to an int.

like image 356
Avrohom Yisroel Avatar asked Oct 28 '25 04:10

Avrohom Yisroel


1 Answers

enum can be a long or other things

public static void Stuff<T>(T val) where T : System.Enum, IConvertible
{
    int v = val.ToInt32(null);
}

This works

If you look at Enum you can see that its not stated as an int. The actual base classes and implementations are:

public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible

BTW: prefer long over int since longs are used as Flags in enumns to allow 64 flags

like image 103
Mitzi Avatar answered Oct 29 '25 19:10

Mitzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!