I seem to have forgotten some of the most basic rules of inheritance because I can’t figure out why this won’t work. I have a class SuffixNode which extends Node.
Node:
class Node
{
public char label;
public Node parent;
public Dictionary<char,Node> children;
public Node(Node NewParent, char NewLabel)
{
this.parent = NewParent;
this.label = NewLabel;
children=new Dictionary<char,Node>();
}
}
SuffixNode:
class SuffixNode: Node
{
public Dictionary<String, int> Location=new Dictionary<String, int>();
public SuffixNode(Node NewParent):base(NewParent, '$')
{
}
public void AddLocation(String loc,int offset)
{
this.Location.Add(loc, offset);
}
}
I’m trying to call the AddLocation method in the main program from the SuffixNode class but it gives me an error saying that no such method exists (in Node class):
Node n;
char FirstChar = suffix[0]; //first character of the suffix
if (suffix == "")
{
return true;
}
//If the first character of a suffix IS NOT a child of the parent
if (!parent.children.ContainsKey(FirstChar))
{
if (FirstChar == '$')
{
n = new SuffixNode(parent);
n.AddLocation(document, offset);
}
else
{
n = new Node(parent, FirstChar); //Create a new node with the first char of the suffix as the label
parent.children.Add(FirstChar, n); //Add new node to the children collection of the parent
}
}
I’m sure it’s an extremely simple answer, but I just can’t realise why this isn’t working. Shouldn’t
Node n = new SuffixNode(parent)
allow me to access the SuffixNode methods and variables?
Many answers have correctly stated that you cannot call a method defined in a derived class on a variable whose type is the base class. None has noted that this is fundamental to the type safety provided by C#’s static typing.
When you call a method on a variable, that method call is resolved at compile time, and there’s no way the compiler can resolve
n.AddLocationwhennis aNode-type variable.The alternative would be to resolve the call at run-time, which could result in an exception if the referent of
nis an instance of some other subclass ofNodethat doesn’t have anAddLocationmethod (or indeed an instance ofNodeitself). The C# type system is explicitly designed to avoid that situtation.Consider:
The philosophy of C# is fail fast: catch coding errors at compile time whenever possible, because errors caught at compile time are much easier to fix than those caught at run time.
The trivial solution, without changing your object model, would be to introduce a new variable inside the relevant block: