I am just starting with Generics in C# but have run into a problem early on, how can I call .HasFlag() on a generic Enum?
public class Example<TEnum> where TEnum : struct {
}
How can I add the [Flags] attribute to it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Calling the instance method will require boxing anyway, so, since you can’t constrain to
Enum, just abandon generics and useEnum. For example, instead of:Do this:
In a generic method, you could achieve your goal like this:
This will throw an exception at runtime if you call the method with a value type that isn’t an enum. You could also cast via
ValueTyperather thanobject, since the type parameter is known to represent a value type: