Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement virtual method of base class and also get the base method implementation in override method in c# [duplicate]

Tags:

c#

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
    }
}
like image 352
Pankaj Kumar Avatar asked Dec 01 '22 12:12

Pankaj Kumar


1 Answers

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();
    }
}
like image 100
lc. Avatar answered Dec 05 '22 01:12

lc.