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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With