C# – ny 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());

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

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

Best Solution

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.

Related Question