Reputation: 13
I have a Base class with a method that a child class will almost always override. However, instead of replacing the base class' method entirely, I would like for whatever is derived in the child class to be added to what is already in the base class.
For Example:
class BaseClass{
public string str()
{
return "Hello my name is" ;
}
}
class ChildClass : BaseClass{
public override string str()
{
return "Sam";
}
}
The point is that if I want to access the str() method by creating an instance of the ChildClass, the string will print out as "Hello, my name is Sam".
I've been looking around and all I have been finding is that this should NOT happen, as the base class shouldn't even know that it is being inherited. So, if the design is false, how would I go about doing this? Keep in mind that there will be multiple child classes inheriting from BaseClass.
Thank you
Upvotes: 0
Views: 2554
Reputation: 75306
If you want to call base class method:
1.Declare the method in base class as virtual
, so that you can override
from child class.
2.Use base
to call method from base class.
internal class BaseClass
{
public virtual string str()
{
return "Hello my name is" ;
}
}
class ChildClass : BaseClass
{
public override string str(){
return base.str() + "Sam";
}
}
Upvotes: 2
Reputation: 4817
First you have to make your method virual
otherwise you can't override it:
public class BaseClass
{
public virual string Str()
{
return "Hello my name is ";
}
}
And then in your child class you can use base
to access the method in your base class.
public class ChildClass : BaseClass
{
public override string Str()
{
return base.Str() + "Sam";
}
}
Upvotes: 0
Reputation: 57899
If you always want to do this, and you don't want to rely on implementers of the derived classes to remember to override the method and call into the base class, you can use a template pattern:
public abstract class BaseClass
{
public string str()
{
return "Hello my name is " + Name;
}
protected abstract string Name { get; }
}
Now any non-abstract class that inherits BaseClass
will be required by the compiler to override Name
, and that value can be consumed by BaseClass
.
public class ChildClass : BaseClass
{
protected override string Name
{
get { return "Sam"; }
}
}
Obviously, this depends on the base class being abstract
.
Upvotes: 8