Tadeusz
Tadeusz

Reputation: 6883

May I to specify from which class I want to call a virtual method?

Let take a test example:

class A
{
    public A() 
    { 
        this.Test(); //I want to call Test exactrly from class A!!! here
    }

    public virtual void Test ()
    {
        Console.WriteLine("I am A!");
    }
}

class B : A
{
    public B() { }

    public override void Test()
    {
        Console.WriteLine("I am B!");
    }
}

//Somewhere in code
B b = new B(); //I want It displays "I am A" instead of "I am B"

Is there a way to do so? P.S.: I know It is a bad design but I want to know in order to improve my knowledge of C#.

Upvotes: 2

Views: 77

Answers (3)

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

You can't if you override the virtual method. But you can do that if you hide it with new instead (even if I wouldn't do that, but you already know that this is bad design :-)).

I mean that if you define your Test method in class B like this:

        public new void Test()
        {
            Console.WriteLine("I am B!");
        }

and then execute it declaring the variable you assign the instance of B as being of type A, you obtain what you want:

A b = new B();
b.Test();

If you want to execute the B version of the method you just have to declare tha variabla as A:

B b = new B();
b.Test();

Upvotes: 0

Martin Booth
Martin Booth

Reputation: 8595

The point of having and overidable metheod is that you can transparently replace functionality and expect the class to function reasonably. What you're asking for is a base class to have knowledge about classes which may derive from this... thats not the principle of OO design.

If you want to call a method which hasn't been overridden.. don't make the method overidable.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500465

No - you can't call a virtual method in a non-virtual way. (Not from C# directly, anyway... you can in IL, but you can't express that in C#.)

In this case, if the code wishing to make the call is in A, then you can just make a non-virtual method containing the behaviour you're interested in, and then potentially call that non-virtual method from the virtual method too.

Upvotes: 3

Related Questions