1

For example in the following program I want entrypoint() in A to be able to call doThis in A, but it calls doThis in B since that's the instance type. How can I achieve what I want?

void Main()
{
    A a = new B();
    a.entrypoint();
}

public class A
{
    public void entrypoint()
    {
        this.doThis(); //doesn't call A::doThis()
    }

    public virtual void doThis()
    {
        Console.WriteLine ("From A");
    }
}

public class B : A
{
    public override void doThis()
    {
        Console.WriteLine ("From B");
    }
}

edit: How can I call the 'base implementation' of an overridden virtual method? is similar but I'm calling the base implementation from base class not main.

edit: similar to How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?

Community
  • 1
  • 1
sgarg
  • 2,340
  • 5
  • 30
  • 42
  • If you override the virtual method in derived class,only the overridden method will be called.If you don't override it the base class method will be invoked – Rangesh Jul 15 '14 at 03:24
  • If you want to call a function in base, then it can't be virtual. – Hai Bi Jul 15 '14 at 03:30

1 Answers1

5

The correct way would arguably be to not call a virtual method if you need it to not be overridden. I'd propose making a private method to do what you want.

itsme86
  • 19,266
  • 4
  • 41
  • 57
  • Making it private actually worked for me even though I thought my whole design was dependent on the virtual function. – sgarg Jul 15 '14 at 03:31
  • I cannot see why it cannot be useful to call a base's version on occasion, and the derived object's implementation as default in all other cases. For example it's no problem in C++ where you just qualify with the base classe's name (even in the base classe's implementation itself), i.e. instead of `this.doThis()` `A::doThis()` – Peter - Reinstate Monica Jul 15 '14 at 04:44
  • @PeterSchneider It's not that it could never be useful, but it definitely has a "code smell" (http://en.wikipedia.org/wiki/Code_smell). It's just screaming out that there's a design flaw. – itsme86 Jul 15 '14 at 14:20
  • @itsme86 Yeah, one should sure know what one's doing, like so often. As an aside, one can utilize managed C++ to do the required job in .net: http://couldbedone.blogspot.de/2007/08/calling-virtual-method-of-class-base-to.html, or reflection, naturally. – Peter - Reinstate Monica Jul 16 '14 at 08:26