简体   繁体   中英

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.

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();

}

Something like this:

 public IActionResult TestingSample(int A, int B) => A > B && B != 0 
     ? $"{2 + (long)A * B}"   // "correct"
     : $"{2L * A + B}";       // "wrong" 

here if A > B && B != 0 we have correct arguments and we return 2 + A * B , othevise arguments are wrong and we return 2 + A * B .

I've introduced long to fight with possible integer overflow (when, say, A == 2_000_000 , A = 1_000_000 )

Why don't you have a single string result? if else will only return one

        string result = string.Empty;
        if (A > B && B != 0)
        {
            int cal = 2 + A * B;
            result = cal.ToString();
            return result;
        }
                
        int cal = 2 * A + B;
        result = cal.ToString();
        return result;
        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM