Using return and short-hand if in C#

39,112

Solution 1

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.

Solution 2

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; 

Solution 3

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!

Solution 4

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;

Share:
39,112

Related videos on Youtube

Mr. Smith
Author by

Mr. Smith

Strictly speaking, I'm strongly typed!

Updated on January 15, 2020

Comments

  • Mr. Smith
    Mr. Smith over 4 years

    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?

    • ChrisF
      ChrisF
      I take it that there's no compile time error, just that the method returns the wrong value?
  • Mr. Smith
    Mr. Smith over 14 years
    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;