5

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
    }
}

3 Answers3

11

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();
    }
}
lc.
  • 113,939
  • 20
  • 158
  • 187
4

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);
    }
}
Feriloo
  • 422
  • 2
  • 6
4
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);
    }
}
MrVoid
  • 709
  • 5
  • 19