Why wouldn't the following line of code work in a method?
return (count > 0) ? true : false;
It works perfectly fine if I do:
bool ret = (count > 0) ? true : false;
return ret;
Bonus Question: Is it really faster or more effective than the standard if statement?
bool ret = false;
if(count > 0)
ret = true;
return ret;
Which one would you recommend?
I would recommend:
return count > 0;
There's no need to explicitly return true
or false
.
Having said that, your compilation error intrigues me. At first sight it looks like it should work. Could you post a short but complete example that fails to compile? The type of that conditional expression should be bool
with no problems. My guess is you've got a more complicated scenario, and by simplifying the example you've removed the real problem.
As for the bonus question: I don't know which would be faster, nor do I care in 99.99% of cases. I'd be amazed to find that it caused any significant delay, unless it prohibited inlining for some reason. Go for the most readable solution - which is the simple return statement, IMO.
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