Is there a generic type-constraint for "where NOT derived from"?

c#, generics

Solution

You could use something like the following:

public interface IFooGenerator
{
    Foo GenerateFoo();
}

interface ISerialFooGenerator : IFooGenerator { }

interface IParallelFooGenerator : IFooGenerator { }

public class FooGenerator : ISerialFooGenerator
{
    public Foo GenerateFoo()
    {
        //TODO
        return null;
    }
}

public class ParallelFooGenerator<T> : IParallelFooGenerator
    where T : ISerialFooGenerator, new()
{
    public Foo GenerateFoo()
    {
        //TODO
        return null;
    }
}

Problem

We can specify a "derived from" constraint on generic type parameters like this: ``` class Bar<T> where T : IFooGenerator ``` Is there a way to specify NOT derived from? My use-case: I have a bunch of `FooGenerator`s that are parallelizable, with the same parallelization code for each, but we don't want them to always be parallelized. ``` public class FooGenerator : IFooGenerator { public Foo GenerateFoo() { ... } } ``` Thus, I create a generic container class for generating Foo in parallel: ``` public class ParallelFooGenerator<T> : IFooGenerator where T : IFooGenerator { public Foo GenerateFoo() { //Call T.GenerateFoo() a bunch in parallel } } ``` Since I want `FooGenerator` and `ParallelFooGenerator<FooGenerator>` to be interchangeable, I make `ParallelFooGenerator : IFooGenerator`. However, I clearly don't want `ParallelFooGenerator<ParallelFooGenerator>` to be legal. So, as an auxiliary question, is there perhaps a better way to design this if "not derived from" constraints are impossible?

Original source

Related problems