Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Class of <T> where T : Enum" not working [duplicate]

Possible Duplicate:
Create Generic method constraining T to an Enum

Is there any reason why we can't do this in C#? And, if possible, how can I do something similar!

What I want :

public class<T> ATag where T : enum {
    [Some code ..]
}

public class<T> classBase where T : enum {
    public IDictionary<T, string> tags { get; set; }
}

So, when it comes the time to call it, I'm sur to get only one of my enum values.

public class AClassUsingTag : classBase<PossibleTags> {
    public void AMethod(){
         this.tags.Add(PossibleTags.Tag1, "Hello World!");
         this.tags.Add(PossibleTags.Tag2, "Hello Android!");
    }
}

public enum PossibleTags {
    Tag1, Tag2, Tag3
}

Error message : "Constraint cannot be special class 'System.Enum'"

Thank you!

like image 299
Simon Dugré Avatar asked Feb 25 '11 17:02

Simon Dugré


People also ask

What is TEnum C#?

TEnum is the Generic type of enumeration. You can pass any of your enumeration to that method. The second method is a non-generic one, where you would use a typeof keyword to identify the enums and return the enum names as a string collection.

How do you use generic enums?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.

How do I find the enum type?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.


2 Answers

You can't do it because the spec says you can't, basically. It's annoying, but that's the way it is. The CLR supports it with no problem. My guess is that when generics were first being designed, the CLR might not have supported it, so it was prohibited in the language too... and either the C# team didn't get the memo about it then being supported, or it was too late too include it. Delegates are similarly annoying.

As for a workaround... have a look at my Unconstrained Melody project. You could use the same approach yourself. I wrote a blog post at the same time, which goes into more details.

like image 118
Jon Skeet Avatar answered Sep 22 '22 04:09

Jon Skeet


it's not possible. But if you are interested in a runtime check you can do

class A<T>
        {
            static A()
            {
                if(!typeof(T).IsEnum)
                {
                    throw new Exception();
                }
            }
        }
like image 39
Bala R Avatar answered Sep 25 '22 04:09

Bala R