3

I have an abstract class A and it having virtual method having with partial implementation and it is inherited in class B. I want implement virtual method in derived class, how should i get the base implementation in derived class. For Example.

public abstract class A
{
    public int Sum { set; get; }
    public virtual void add(int a, int b)
    {
        Sum = a + b;
    }
}
class B : A
{
    public override void add(int a, int b)
    {
        // what should i write here
    }
}


  • @Derlin I do not think it would be fair to use a C++ thread for the duplicate link (how basic this topic may seem). - Jeppe Stig Nielsen
  • oops, sorry, I misread. I thought it was C++, not C#. - Derlin
  • I'm still pretty sure this question has been asked before, also in the context of C# - Sentry

3 답변


7

Overriding a virtual method does just that, overrides the default (base) implementation and replaces it with a new one. However, if you do not provide any overridden implementation for a virtual method, you automatically get the base implementation. So, the answer to your question is simply do not override the add method in the first place:

class B : A {}

However, if you need to keep the base implementation but wish to extend it, you can explicitly call the base implementation from a derived class, with the base keyword. For example:

class B : A
{
    public override void add(int a, int b)
    {
        base.add(a, b);
        DoSomethingElse();
    }
}


  • This is the right answer! - MrVoid

3

public abstract class A
{
    public int Sum { set; get; }
    public virtual void add(int a, int b)
    {
        Sum = a + b;
    }
}

class B : A
{
    public override void add(int a, int b)
    {
        //do your sufff

        //call base method of class A
        base.add(a, b);
    }
}


3

Simply call your base class function:

class B : A
{
    public override void add(int a, int b)
    {
        // do operation related to derived class 
        // call your base function
        base.add(a, b);
    }
}

Linked


Related

Latest