Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using return and short-hand if in C#

Tags:

syntax

c#

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?

like image 653
Mr. Smith Avatar asked Sep 08 '09 08:09

Mr. Smith


1 Answers

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.

like image 78
Jon Skeet Avatar answered Oct 21 '22 13:10

Jon Skeet