I would like to know if it is possible to access the base virtual method using a inheriting class (which overrides the method) object.
I know this is not a good practice but the reason I want to know this is if it is technically possible. I don't follow such practice, asking just out of curiosity.
I did see a few similar questions but I did not get the answer I am looking for.
Example:
public class Parent
{
public virtual void Print()
{
Console.WriteLine("Print in Parent");
}
}
public class Child : Parent
{
public override void Print()
{
Console.WriteLine("Print in Child");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
//or Parent child = new Child();
child.Print(); //Calls Child class method
((Parent)c).Print(); //Want Parent class method call
}
}
As per the linked duplicate I commented with, you can do it with some reflection tricks as such:
static void Main(string[] args)
{
Child child = new Child();
Action parentPrint = (Action)Activator.CreateInstance(typeof(Action), child, typeof(Parent).GetMethod("Print").MethodHandle.GetFunctionPointer());
parentPrint.Invoke();
}
Nope - it is not possible to invoke the Virtual method of Base class - The most derived implementation of the method is invoked in such scenarios. In the example given by you, it would print "Print in Child"
in both the cases.
According to me, the best you can do is:
public class Parent
{
public virtual void Print()
{
Console.WriteLine("Print in Parent");
}
}
public class Child : Parent
{
public override void Print()
{
base.Print();
Console.WriteLine("Print in Child");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
//or Parent child = new Child();
child.Print(); //Calls Child class method
((Parent)c).Print(); //Want Parent class method call
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With