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.
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>
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With