Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to call the parent version of an overridden method? (C# .NET)

In the code below I tried in two ways to access the parent version of methodTwo, but the result was always 2. Is there any way to get the 1 result from a ChildClass instance without modifying these two classes?

class ParentClass {     public int methodOne()     {         return methodTwo();     }      virtual public int methodTwo()     {         return 1;     } }  class ChildClass : ParentClass {     override public int methodTwo()     {         return 2;     } }  class Program {     static void Main(string[] args)     {         var a = new ChildClass();         Console.WriteLine("a.methodOne(): " + a.methodOne());         Console.WriteLine("a.methodTwo(): " + a.methodTwo());         Console.WriteLine("((ParentClass)a).methodTwo(): "          + ((ParentClass)a).methodTwo());         Console.ReadLine();     } } 

Update ChrisW posted this:

From outside the class, I don't know any easy way; but, perhaps, I don't know what happens if you try reflection: use the Type.GetMethod method to find the MethodInfo associated with the method in the ParentClass, and then call MethodInfo.Invoke

That answer was deleted. I'm wondering if that hack could work, just for curiosity.

like image 993
Jader Dias Avatar asked Jan 13 '09 13:01

Jader Dias


People also ask

How do you call superclass version of an overriding method in sub class?

The overridden method shall not be accessible from outside of the classes at all. But you can call it within the child class itself. to call a super class method from within a sub class you can use the super keyword.

Are overridden methods inherited?

Overridden methods are not inherited.

How do you call an overridden function?

To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.


1 Answers

Inside of ChildClass.methodTwo(), you can call base.methodTwo().

Outside of the class, calling ((ParentClass)a).methodTwo() will call ChildClass.methodTwo. That's the whole reason why virtual methods exist.

like image 107
Craig Stuntz Avatar answered Sep 18 '22 15:09

Craig Stuntz