MyDaftQuestions MyDaftQuestions - 21 days ago 6
C# Question

Extension Method on enum parameter must be constrained to a struct

I've seen some code http://stackoverflow.com/a/479417/1221410

It is designed to take an enum value and get the description. The relevant part is:

public static string GetDescription<T>(this T enumerationValue) where T : struct


I'm using the same code but what has confused me is I can't change the constraint

public static string GetDescription<T>(this T enumerationValue) where T : enum

public static string GetDescription<T>(this T enumerationValue) where T : class


2 issue have arisen from this.

The first is when I use the
enum
as the constraint parameter. This should constrain the generic parameter to an enum. If so, why can't I type code like

var a = "hello world";


within the function. That has nothing to do with the parameter...

My second question is, when I change the constraint to
class
, then the above code snippet (
var a = "hello world";
) works fine but when I call the function I get the error message

'Enum.Result' must be a reference type in order to use it as parameter 'T' in the generic type or method 'GetDescription<T>(T)'


Enum.Result must be a reference type
... I thought a class was a reference type...

Why does the example at http://stackoverflow.com/a/479417/1221410 only work with
struct
?

Answer

The Problem why T : class won't work is because an enum always is a struct. So you see it the wrong way. You write:

Enum.Result must be a reference type... I thought a class was a reference type...

You are right that a class is a reference type. But Enum.Result isn't a class. It's a struct as mentioned above. Your constraint T : class just accept a reference type.

Further you can't type var a = "hello world"; in your function if you change constraint to T : enum, because this constraint isn't valid. So you wouldn't be able to write any valid code in your method before you fix your constraint.

Take a look at msdn for clarify which constraints are possible.

Comments