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!
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.
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.
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.
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();
}
}
}
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