Is there any way to call the parent version of an overridden method? (C# .NET)
At the IL level, you could probably issue a call
rather than a callvirt
, 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 the virtual
and it works fine; too clever by half...)
Inside the ChildClass
type, you can use base.methodTwo()
- however, this is not possible externally. Nor can you go down more than one level - there is no base.base.Foo()
support.
However, if you disable polymorphism using method-hiding, you can get the answer you want, but for bad reasons:
class ChildClass : ParentClass
{
new public int methodTwo() // bad, do not do
{
return 2;
}
}
Now you can get a different answer from the same object depending on whether the variable is defined as a ChildClass
or a ParentClass
.
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.