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.
At the IL level, you could probably issue a
callrather than acallvirt, and get the job done – but if we limit ourselves to C# ;-p (edit darn! the runtime stops you:VerificationException: ‘Operation could destabilize the runtime.’; remove thevirtualand it works fine; too clever by half…)Inside the
ChildClasstype, you can usebase.methodTwo()– however, this is not possible externally. Nor can you go down more than one level – there is nobase.base.Foo()support.However, if you disable polymorphism using method-hiding, you can get the answer you want, but for bad reasons:
Now you can get a different answer from the same object depending on whether the variable is defined as a
ChildClassor aParentClass.