1

I have created a generic method. The typeparameter could be any enum:

private AdditionalFields GetAdditionalFields<T>(params T[] fields) where T : struct, Enum
{
  var fieldTextList = new List<string>();
  foreach ( var field in fields )
  {
    fieldTextList.Add($"F{(int)field}");   // <- Error here
  }
  // ... do logic
  return ...
}

When I try to cast the enum-value to a integer, i get the compiler-error "Cannot convert type 'T' to 'int'.

Can someone explain, why this happens? T is always an enum and therefore should able to be converted to int - or not?

BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • 2
    Not all enums use `int` internally -- you can define an enum which uses any integral numeric type. The compiler doesn't know which type you've given it, and so it doesn't know what instruction to use to convert it to an int. You can use `Convert.ToInt32(field)` though, although you'll incur a box – canton7 Jan 04 '21 at 14:00
  • @canton7: You are absolutely right, but the answer box is a little bit further down. :-) – Heinzi Jan 04 '21 at 14:27
  • @canton7 The "price" of boxing is probably quite irrelevant in this case, considering that he is formatting strings (normally something more expensive) – xanatos Jan 04 '21 at 14:28
  • Why constraint on struct and Enum instead of just Enum? Why it compiles ? –  Jan 04 '21 at 14:29
  • You can `ToString("D")` and you'll get the numeric value of the enum stringified – xanatos Jan 04 '21 at 14:31
  • 1
    @Heinzi That answer is a duplicate for sure -- I've answered similar questions before. Answers on duplicates get down-voted, but I like to be at least a bit helpful before I hit the search box. That said, this specific question is better answered by Serg's approach, so I'm not going to mark it as a dup – canton7 Jan 04 '21 at 14:36
  • 1
    @xanatos Agreed. However, this is SO -- if I hadn't written that, someone would have gone to some pains to point it out, I can guarantee. I find it's best to mention that sort of stuff upfront to nip it in the bud (as it turns out, it didn't work in this instance) – canton7 Jan 04 '21 at 14:39
  • 1
    @OlivierRogier It stops someone from writing `GetAdditionalFields(...)` -- the `Enum` constraint allows `T` to be `Enum` itself: adding `struct` forces `T` to be a specific type of enum. – canton7 Jan 04 '21 at 14:41
  • @canton7: Makes sense. – Heinzi Jan 04 '21 at 14:43

1 Answers1

3

I think, it's better to use enum-specific format string to get integer representation of enum (integer in general meaning, not only int32)

fieldTextList.Add($"F{field:D}");

You can find more about format specifiers for enums here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/enumeration-format-strings#d-or-d

Serg
  • 3,454
  • 2
  • 13
  • 17