Access Parent Class virtual method from inheriting Child Class Object
c#, inheritance, oop
Solution
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();
}
Problem
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 } } ```