Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Parent Class virtual method from inheriting Child Class Object

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
    }
}
like image 579
Shakti Prakash Singh Avatar asked Jan 25 '13 04:01

Shakti Prakash Singh


3 Answers

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();
}
like image 194
Jesse C. Slicer Avatar answered Sep 27 '22 00:09

Jesse C. Slicer


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.

like image 20
Mayur Manani Avatar answered Sep 23 '22 00:09

Mayur Manani


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
    }
}
like image 26
mihirj Avatar answered Sep 27 '22 00:09

mihirj