tags:

views:

941

answers:

4

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 return = false;

if(count > 0)
{
    ret = true;
}

return ret;

Which one would you recommend?

+26  A: 

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.

Jon Skeet
+1. Except in some (rare) cases, readability > all.
Clement Herreman
Thanks Jon, the problem was a simple syntax error that went unnoticed (usually until AFTER you ask what's wrong on SO). I like this answer, it's even shorter! return count > 0;
Mr. Smith
man you always beat me to it ...
Alex Baranosky
+6  A: 

try this:

return count > 0;

before return returns the expression count > 0 is evaluated and gives true or false.

this should also work:

return (count > 0 ? true : false);

but I'd recommend you didn't do this.

I always try to keep the amount of horizontal operations low, I believe it makes it easier to read code.

just imagine the following scenario which will just confuse :)

return count > 0 ? false : true;
Makach
+1  A: 

this works

return (count > 0 ? true : false);

You can then make it return other values than true and false. In your particular case I would do like the other suggestions; return count > 0;

sindre j
+5  A: 

From the point of view of C#

return count > 0;

is better for it's readabilty.

But the compiler optmize the code, so your three options are actually the same once compiled. You could try to look at the IL code to verify!

ema