Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract with inheritor as field

Tags:

c#

.net

I'm making a program with multiple types of binary trees in it. So I decided to make an abstract class, to avoid copying code over. But there is a problem, the nodes of each tree need to contain children that are the same type as the node itself. Is there any means to define this in the abstract, or should I just make different classes for each type after all?

public abstract class BinaryNodeAbstract<T>
{
    public T Value;
    public BinaryNodeAbstract<T> Left;
    public BinaryNodeAbstract<T> Right;

The way it is now, the nodes could be of any type BinaryNode. That is what needs to be avoided.

like image 246
Ozitiho Avatar asked Oct 02 '14 13:10

Ozitiho


1 Answers

You should include the parent type too, to keep the inherited type on Left and Right (else you can't use the inherited type on the implementer):

public abstract class BinaryNodeAbstract<T, L> where L : BinaryNodeAbstract<T, L>
{
    public T Value;
    public L Left;
    public L Right;
}

You can use it like this:

public class BinaryNodeImplementation : BinaryNodeAbstract<int, BinaryNodeImplementation>
{
}
like image 167
Patrick Hofman Avatar answered Oct 22 '22 13:10

Patrick Hofman