3

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.

Avrohom Yisroel
  • 8,555
  • 8
  • 50
  • 106
  • 2
    I don't understand why the question was closed. The question above is asking to understand why something can't be done. In this case - enum itself can inherit from 'short', 'byte', 'int' etc. So the compiler has no way of telling what the Enum's parent type is. The referenced answer that closed this question is a hack/workaround - and should not be done in sophisticated coding environments. – Rikki Dec 06 '20 at 22:30

1 Answers1

5

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

Mitzi
  • 2,652
  • 1
  • 20
  • 15
  • Thanks, shows how much you can learn from reading the docs! I had tried `IConvertible` without success, and had resorted to using `Convert.ToInt32()`. This worked, but it niggled me that my first line of code worked fine. I wondered if it could be made generic. I see now that it can't. Thanks. – Avrohom Yisroel Dec 06 '20 at 22:48