I have the following class hierarchy
class A
{
public virtual string M()
{
return M(String.Empty);
}
public virtual string M(string s)
{
return M(s, false);
}
public virtual string M(string s, bool flag)
{
// Some base logic here
}
}
class B:A
{
public override string M(string s, bool flag)
{
string baseResult = base.M(s);
// Derived class logic here
}
}
The class B can be used in two cases:
1)
A b = new B();
string result = b.M();
2)
B b2 = new B();
string result2 = b2.M(someString, true);
Both cases crash with StackOverflowException. This happens because base.M(s) which is called inside B.M(string s, bool flag) will call B.M(string s, bool flag) again.
Is there any good way to avoid this?
I understand that if I call base.M(s, flag) everything will work, but what if someone else develops a dervived class and access base.M(s) ? I don't like to leave a possibility of StackOverflowException here.
SOLUTION
Now my hierarchy will look like
class A
{
public string M()
{
return M(String.Empty, false);
}
public virtual string M(string s, bool flag)
{
// Some base logic here
}
}
class B:A
{
public override string M(string s, bool flag)
{
string baseResult = base.M(s, flag);
// Derived class logic here
}
}
Usually the trick here is to have one virtual
(usually the one with most parameters), and this is the only one you call vertically. The others might be non-virtual and just call the "main" one with appropriate defaults.
I would go with something like this:
class A
{
public virtual string M(string s = "", bool flag = false)
{
// Some base logic here
}
}
instead of having 3 overloaded methods which all end up calling the same method with hard-coded parameters.
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