MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Extension Method on enum parameter must be constrained to a struct

I've seen some code https://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 https://stackoverflow.com/a/479417/1221410 only work with struct?

Upvotes: 0

Views: 530

Answers (2)

Steve
Steve

Reputation: 1316

As the comments say, enum is not a class. However, Enum is. It's just a special one and if you try to constrain the type like that, it won't let you:

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

Constraint cannot be special class 'Enum'

The existing code from the question you linked is about the best you can do but see here if you want more info: Create Generic method constraining T to an Enum

As to the second part of your question, about constraining it to 'class' instead, there must be something else going on there.

Edit - I'm dumb - what Sebi said. :)

There is no Enum.Result in either your code snippets or the answer you linked to so I think we'll need to see more of your code to answer that one.

Upvotes: 1

Sebi
Sebi

Reputation: 3979

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.

Upvotes: 1

Related Questions