Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you use "where T: struct" for generic enum extension methods in C#?

Tags:

c#

I've seen examples of generic extension methods in C# for enumerations that use where T: struct, also another that uses where T: IComparable. For example, in the former case:

public static class EnumExtensionMethods
{
  public static string Description<T>(this T enumValue) where T : struct
  {
    // ...
  }
}

I'm confused why the constraint requires that type T must be a struct. I'd expect it to be where T : Enum. Can someone explain this to me? As a bonus item, maybe also explain why IComparable is also used in some examples.

FWIW, I did my research on this. I can find explanations on why IComparable is used, for example in this question, but it doesn't seem conclusive, nor do they explain why struct is used in conjunction.

like image 487
void.pointer Avatar asked Dec 01 '22 13:12

void.pointer


1 Answers

I suspect you're looking at some code that was written before C# 7.3 - the ability to constrain a generic type parameter using Enum or Delegate was only introduced in C# 7.3.

But for extension methods targeting enums, you'd want both Enum and struct in the constraint, e.g.

public static string GetDescription<T>(this T enumValue) where T : struct, Enum
{
    // ...
}

That way it can only be called on concrete enum types, rather than GetDescription<Enum>(null).

like image 178
Jon Skeet Avatar answered Dec 10 '22 06:12

Jon Skeet