Imagine you have a class hierarchy as:
class Base
{
public virtual string GetName()
{
return "BaseName";
}
}
class Derived1 : Base
{
public override string GetName()
{
return "Derived1";
}
}
class Derived2 : Base
{
public override string GetName()
{
return "Derived2";
}
}
In most appropriate way, how can I write the code in a way that all "GetName" methods adds "XX" string to return value in derived class?
For example:
Derived1.GetName returns "Derived1XX"
Derived2.GetName returns "Derived2XX"
Changing the code of GetName method implementation is not good idea, because there may exist several derived types of Base.
Leave GetName
non-virtual, and put the "append XX" logic in that function. Extract the name (without "XX") to a protected virtual function, and override that in the child classes.
class Base
{
public string GetName()
{
return GetNameInternal() + "XX";
}
protected virtual string GetNameInternal()
{
return "BaseName";
}
}
class Derived1 : Base
{
protected override string GetNameInternal()
{
return "Derived1";
}
}
class Derived2 : Base
{
protected override string GetNameInternal()
{
return "Derived2";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With