tags:

views:

64

answers:

4

Sorry for asking silly question

Is it possible to enforce constraint on generic in such a way that the given T can be derived from any reference Type except some A,B,C (where A,B,C are reference types). (i.e)

Where T : class except A,B,C
+3  A: 

No, you can only specify that it does inherit from a particular type, is a value or reference type, or that it must have a default constructor. Remember that this is for the benefit of the compiler, not the developer. :)

The best you could probably do is throw an exception at run time.

GraemeF
+1  A: 

Sorry No. You can find out how you can constrain here...

Jason Punyon
+3  A: 

No. But you could check for these classes at run-time:

public class Foo<T>
{
    static Foo()
    {
        // one of the following depending on what you're trying to do
        if (typeof(A).IsAssignableFrom(typeof(T)))
        {
            throw new NotSupportedException(string.Format(
                "Generic type Foo<T> cannot be instantiated with {0} because it derives from or implements {1}.",
                typeof(T),
                typeof(A)
                ));
        }

        if (typeof(T) == typeof(A))
        {
            throw new NotSupportedException(string.Format(
                "Generic type Foo<T> cannot be instantiated with type {0}.",
                typeof(A)
                ));
        }
    }
}
dtb
If you move the check to a static constructor, it only runs once instead of every time a new instance of the class is created. However, due to debugging issues it's very important to include a proper error message with the `NotSupportedException` in that case. I edited the post to use that method.
280Z28
A: 

No. There is no negation of types. The where clause only allows you to contrain to a specific type.

Scott Frye