首页 > 解决方案 > C# get Result from IF Statement

问题描述

I have a simple code like:

public IActionResult TestingSample(int A, int B)
    {
        if (A > B && B != 0)
        {
            int corr = 2 + A * B;
            string rescorr = corr.ToString();
        }
        else
        {
            int wron = 2 * A + B;
            string reswron = wron.ToString();
        }
    }

From the code above, I want to add a result with: rescorr + reswron. So it becomes string result. How can I write the return value with string like that?

Really appreciated.
Thank you.

标签: c#

解决方案


You should probably start by moving your string variables out of the if blocks

And then return the concatenated string.

public IActionResult TestingSample(int A, int B)
{
    string rescorr = string.Empty;
    string reswron = string.Empty;

    if (A > B && B != 0)
    {
        int corr = 2 + A * B;
        rescorr = corr.ToString();
    }
    else
    {
        int wron = 2 * A + B;
        reswron = wron.ToString();
    }

    return rescorr + reswron;
}

Then you realise that only 1 of these will ever get set so we change the string assignments in to individual returns. We get get rid of the variables and the else block because that's now redundant too.

public IActionResult TestingSample(int A, int B)
{
    if (A > B && B != 0)
    {
        int corr = 2 + A * B;
        return corr.ToString();
    }

    int wron = 2 * A + B;
    return wron.ToString();

}

推荐阅读