This question already has answers here:
Closed 9 years ago.
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!
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.
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();
}
}
}
No I don't believe so. Yes use a design pattern to get around it, have the base class return the type that's allowed, and the derived classes can check for it.
HTH.