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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With