Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic constraint exclusion

Tags:

c#

generics

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
like image 403
user196546 Avatar asked Jan 23 '23 23:01

user196546


1 Answers

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)
                ));
        }
    }
}
like image 140
dtb Avatar answered Feb 03 '23 21:02

dtb