7wp
7wp

Reputation: 12694

Force to call virtual base function instead of the overriden one

In the following example "Test that v1 function was called" fails. Is there a way to force call the base implementation of "RunFunction" through an instance of "class V2" ?

    class V1 
    {
        public virtual string RunFunction()
        {
            return "V1";
        }
    }

    class V2 : V1
    {
        public override string RunFunction()
        {
            return "V2";
        }
    }



    [Test]
    public void TestCall()
    {
        var v1 = (V1)new V2();
        var v2 = new V2();

        Assert.IsTrue(v1.RunFunction() == "V1", "Test that v1 function was called");
        Assert.IsTrue(v2.RunFunction() == "V2", "Test that v2 function was called");
    }

Thanks for looking, guys and gals.

Upvotes: 0

Views: 1215

Answers (3)

Kennet Belenky
Kennet Belenky

Reputation: 2753

You could accomplish what you want with Reflection.

However, while it is unclear to me what your ultimate goal is, it is clear to me that you don't actually want to do what you're asking for. I suggest you spend some time re-educating yourself on polymorphism, and object oriented programming.

Upvotes: 1

Steve Cooper
Steve Cooper

Reputation: 21490

I think you might get away with public new string RunFunction() in the subclass, but I'd also suggest that if V2 isn't supposed to provide it's own specific behaviour, then using inheritance isn't the right approach.

You could also try defining a static on the base -- public static string RunFuctionStatic(V1 item), then called as V1.RunFunctionStatic(v2Instace).

Upvotes: 1

Justin Ethier
Justin Ethier

Reputation: 134227

The whole point of class inheritance is that it allows you to override selected base class behavior.

You can use the base keyword from within V2 to call into base-class code from V1, but you cannot do that outside of the class. Just as a quick example of usage:

class V2 : V1
{
    public override string RunFunction()
    {
        return base.RunFunction();
    }
}

Alternatively you could instantiate an instance of V1:

var v1 = new V1();

Upvotes: 4

Related Questions