sgarg
sgarg

Reputation: 2459

How to make base class call its virtual function?

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?

Upvotes: 1

Views: 114

Answers (1)

itsme86
itsme86

Reputation: 19496

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.

Upvotes: 5

Related Questions