Search code examples
c#generics

C# cross referencing generic classes


I want two generic classes to be able to reference each other. I can't seem to get anything to compile. Tried this:

class Program
{
    static void Main(string[] args)
    {
    }

    public class ClassA<BT> where BT: ClassB<ClassA<BT>>
    {
        BT btvar;
    }

    public class ClassB<AT> where AT: ClassA<ClassB<AT>>
    {
        AT atvar;
    }
}

This has a practical implementation, but I wanted to avoid a complicated explanation of my own code. I can create closed classes that obey the rule, I just can't seem to describe a generic class or interface for those closed instances.


Solution

  • As fas as I understand, this is impossible, and this is why:

    You want A, with a template value of type B. You want B, with a template value of type A.

    If you create a new instance of A, the compiler has to check of T is of type B. To check if it's type B, it has to check if B is of type A, A of type B, etc etc.

    You end up creating an endless loop.