Jay
Jay

Reputation: 1003

Parent/Child Generics Relationship

So, I'm trying to have a parent/child class relationship like this:

class ParentClass<C, T> where C : ChildClass<T>
{
    public void AddChild(C child)
    {
        child.SetParent(this); //Argument 1: cannot convert from 'ParentClass<C,T>' to 'ParentClass<ChildClass<T>,T>'
    }
}
class ChildClass<T>
{
    ParentClass<ChildClass<T>, T> myParent;
    public void SetParent(ParentClass<ChildClass<T>, T> parent)
    {
        myParent = parent;
    }
}

But, this is a compile error. So, my second thought was to declare the SetParent method with a where. But the problem is that I don't know what type declare myParent as (I know the type, I just son't know how to declare it.)

class ParentClass<C, T> where C : ChildClass<T>
{
    public void AddChild(C child)
    {
        child.SetParent(this);
    }
}
class ChildClass<T>
{
    var myParent; //What should I declare this as?
    public void SetParent<K>(ParentClass<K,T> parent) where K : ChildClass<T>
    {
        myParent = parent;
    }
}

Upvotes: 7

Views: 632

Answers (1)

Paul Bellora
Paul Bellora

Reputation: 55213

This seems to compile, though it's rather hairbrained:

class ParentClass<C, T> where C : ChildClass<C, T>
{
    public void AddChild(C child)
    {
        child.SetParent(this);
    }
}
class ChildClass<C, T> where C : ChildClass<C, T>
{
    ParentClass<C, T> myParent;
    public void SetParent(ParentClass<C, T> parent)
    {
        myParent = parent;
    }
}

This solution makes use of a recursively bound type parameter, which approximates the "self-type".

I'm obligated to link to Eric Lippert's article on this pattern: Curiouser and curiouser

Upvotes: 4

Related Questions