Nested generic interface, but don't mix concrete implementations in the nesting

Viewed 34

I have this generic interface with the following implementations:

public interface IInterface<T, U> where U : IInterface<T, U> {}
public class ConcreteA<T> : IInterface<T, ConcreteA<T>> {}
public class ConcreteB<T> : IInterface<T, ConcreteB<T>> {}

I also wrote the following method to flatten nested interfaces. The idea is that if I have a ConcreteA<ConcreteA<T>> object, that's redundant, and I can just apply some logic to obtain a simple ConcreteA<T>.

public static S Flatten<R, S, T>(this R nested)
    where R : IInterface<S, R>
    where S : IInterface<T, S> { 
    // logic to flatten the input
}

The problem is that I only want to flatten things if both layers of the nested input are the same concrete implementation of the interface, e.g., ConcreteA<ConcreteA<T>> but not ConcreteB<ConcreteA<T>>; the flattening code will give a wrong result if you mix concrete implementations. The compiler will not enforce this for my method, so I would need to check it at runtime using reflection for generics, which I would rather avoid.

What should I do so that calling Flatten() on ConcreteA<ConcreteA<T>> compiles but calling on ConcreteB<ConcreteA<T>> fails to compile?

0 Answers
Related