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.
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.
Overridden methods are not inherited.
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.
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.
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