The book on "C# 3.0- The Complete Reference" (p.295)says:
The program creates a base class called Base and two derived classes, called Derived1 andDerived2. Base declares a method called Who( ), and the derived classes override it. Inside the Main( )method, objects of type Base, Derived1, and Derived2 are declared. Also, a reference of type Base, called baseRef, is declared. The program then assigns a reference to each type of object to baseRef and uses that reference to call Who( ). As the output shows, the version of Who( )executed is determined by the type of object being referred to at the time of the call, not by the class type of baseRef
Now the point is that ,is it necessary that we should use a basereference and assign to it the object of each derived class in order to take advantage of method overriding and virtual keyword as i already tested that it worked correctly too ,instead when i didn't use any basereference.
Here you go:
class Base
{
// Create virtual method in the base class.
public virtual void Who()
{
Console.WriteLine("Who() in Base");
}
}
class Derived1 : Base
{
// Override Who() in a derived class.
public override void Who()
{
Console.WriteLine("Who() in Derived1");
}
}
class Derived2 : Base
{
// Override Who() again in another derived class.
public override void Who()
{
Console.WriteLine("Who() in Derived2");
}
}
class Program
{
static void Main(string[] args)
{
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; // a base-class reference
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who();
//but this works too the same
baseOb.Who();
dob1.Who();
dob2.Who();
}
}
}
Be brave enough to answer it rather than downvote !!!