How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?
I know we can call Method2 in the Base class from a method in the Derived class by using base.Method2() but what I want to do is calling it from the other virtual method in the Base class. Is it possible?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args )
{
Base b = new Derived( );
b.Method1( );
}
}
public class Base
{
public virtual void Method1()
{
Console.WriteLine("Method1 in Base class.");
this.Method2( ); // I want this line to always call Method2 in Base class, even if the current instance is a Derived object.
// I want 'this' here to always refer to the Base class. Is it possible?
}
public virtual void Method2()
{
Console.WriteLine( "Method2 in Base class." );
}
}
public class Derived : Base
{
public override void Method1()
{
Console.WriteLine( "Method1 in Derived class." );
base.Method1();
}
public override void Method2()
{
Console.WriteLine( "Method2 in Derived class." );
}
}
}
With the above codes, it will output:
Method1 in Derived class.
Method1 in Base class.
Method2 in Derived class.
while what I would expect is:
Method1 in Derived class.
Method1 in Base class.
Method2 in Base class.