In an online C# tutorial [1] there is the following statement:
"The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference."
I tested this with the following code:
using System;
class Program {
static void Main(string[] args) {
Father p1 = new Son();
Son p2 = new Son();
p1.print();
p2.print();
Console.ReadLine();
}
}
class Father {
public virtual void print() {
Console.WriteLine("Father");
}
}
class Son : Father {
public override void print() {
Console.WriteLine("Son");
}
}
However, I get this result:
Son
Son
It looks to me that p1 is in fact being referenced as the base class, and should therefore not be overridden. Am I misunderstanding? Is the tutorial wrong? I looked in MSDN [2] and it seems to confirm:
"At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed."
[1] http://www.csharp-station.com/Tutorials/Lesson09.aspx
[2] http://msdn.microsoft.com/en-us/library/ms173152.aspx