As title says, I'd like to know if it is possible.
I have a node class that points to another node in the same data structure.
class DataStructure<T, N>
where T : IComparable<T>
where N : Node<T> {
N RootNode;
// More code to follow, etc.
}
class Node<T>
where T : IComparable<T> {
T value;
Node<T> NextNode;
Node<T> GetLastNode() {
Node<T> current = this;
while (this.NextNode != null) {
current = current.NextNode;
}
return current;
}
// etc.
}
I want to be able to expand the Node class though, in order to have more information for certain generic version of the DataStructure
. For example:
class AdvancedNode<T> : Node<T>
where T : IComparable<T> {
int Height;
int Size;
// etc.
}
The problem with this is when I try to follow the NextNode
link.
DataStructure<char, AdvancedNode<char>> d = new DataStructure<char, AdvancedNode<char>>();
d.RootNode = new AdvancedNode<char>();
d.RootNode.NextNode = new AdvancedNode<char>();
AdvancedNode<char> y = d.RootNode.NextNode; // TYPE ERROR! Will not compile
Additionally, I want to make it so that it is not possible to do something like this:
DataStructure<char, AdvancedNode<char>> d = new DataStructure<char, AdvancedNode<char>>();
d.RootNode = new AdvancedNode<char>();
d.RootNode.NextNode = new Node<char>(); // This will compile,
// but I don't want it to!
Is there some way to enforce at build time that Node.NextNode
will be the same type as this
? I'd like to be able to implement a generic data structure without needing to do casting. Is it possible? Am I using an inferior design pattern?