简体   繁体   中英

from a bool function return false inside a loop in C#

I was recently told that it is a bad practise to return false from inside a loop, though it might not actually be called more than once. Is it better to have a secondary flag to actually break out of the functions?

foo()
{
  if(bar)
    //somecode
  else
    //some other code
}
private static bool bar(int x)
{
for(int i=0;i<10;i++) 
{
    if(i<x)
    {
         return false;
         break;
    }
    //some operation 
}

Is this break statement necessary, considering the boolean function has already returned out of it by then

The Break statement is unnecessary

Here's why

IL code for foo()

bool flag = this.bar();
if (flag)
{
    // some commented code
}

and in IL code for bar() below

Notice the there is no

break;

after the line

return result;

private bool bar()
{
    bool result;
    int num;
    for (int i = 0; i < 10; i = num + 1)
    {
        bool flag = i < 1;
        if (flag)
        {
            result = false;
            return result;
        }
        num = i;
    }
    result = true;
    return result;
}

break;

is actually removed by the C# compiler when compiling to IL Code

Usually

return is indicator to exit the method and return the result.

break is used when you want to exit the loop, iterative processes.

i think it's not best approach, but you can do that, at least the compiler will know what to do however suggesting you the warning.

you should see the break warning

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