Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# inheritance help

Tags:

c#

inheritance

I am fairly new to inheritance and wanted to ask something. I have a base class that has lots of functionality that is shared by a number of derived classes.

The only difference for each derived class is a single method called Name. The functionality is the same for each derived class, but there is a need for the Name distinction.

I have a property in the base class called Name. How do I arrange it so that the derived classes can each override the base class property?

Thanks.

like image 315
Darren Young Avatar asked Dec 02 '22 04:12

Darren Young


1 Answers

Declare your method as virtual

public class A
{
    public virtual string Name(string name)
    {
        return name;
    }
}
public class B : A
{
    public override string Name(string name)
    {
        return base.Name(name); // calling A's method
    }
}
public class C : A
{
    public override string Name(string name)
    {
        return "1+1";
    }
}
like image 95
BrunoLM Avatar answered Dec 04 '22 18:12

BrunoLM