Search code examples
c#genericsenumsgeneric-method

Cast enum-value in generic method to int


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?


Solution

  • 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