Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call base overloaded method in c#?

Tags:

c#

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
    }
}
like image 949
Aides Avatar asked Feb 25 '23 06:02

Aides


2 Answers

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.

like image 197
Marc Gravell Avatar answered Mar 07 '23 08:03

Marc Gravell


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.

like image 38
Rob Avatar answered Mar 07 '23 09:03

Rob