Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference using if/else vs just if before a return statement?

Tags:

c#

asp.net

I found it hard to search for this question.

Will the else statement make any difference in the code below?

public string Test()
{
  if (statement) return "a";
  else return "b";
}  

What's good practice in this case?

like image 823
Niklas Avatar asked Mar 09 '26 08:03

Niklas


2 Answers

No, it will not make any difference in this case, since if the if-statement is true, it will return and never go to the return "b"; line regardless of the if.

In this case, I usually omit the else, but I don't know if that is what the majority will do in this case.

like image 153
Øyvind Bråthen Avatar answered Mar 11 '26 01:03

Øyvind Bråthen


There is no difference, in fact they both compile down to the same IL:

public bool GetValue(bool input)
{
    if (input) return true;

    return false;
}

IL_0000:  ldarg.1     
IL_0001:  brfalse.s   IL_0005
IL_0003:  ldc.i4.1    
IL_0004:  ret         
IL_0005:  ldc.i4.0    
IL_0006:  ret  

And:

public bool GetValue2(bool input)
{
    if (input)
        return true;
    else
        return false;
}

IL_0000:  ldarg.1     
IL_0001:  brfalse.s   IL_0005
IL_0003:  ldc.i4.1    
IL_0004:  ret         
IL_0005:  ldc.i4.0    
IL_0006:  ret   
like image 37
Matthew Abbott Avatar answered Mar 11 '26 00:03

Matthew Abbott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!