开发者

What does this method's return statement return?

I saw a method written in C# that returns a boolean value. The method's return statement looks like this:

return count > 0;开发者_运维百科

If I'm reading this correctly, it returns a value if count is greater than zero. What happens if the value of 'count' is not greater than 0? What gets returned? Zero? If that's the case, couldn't the return statement just say:

return count;


No, it's an expression that returns a boolean value, so

return count > 0;

Returns true if count is 1+, false otherwise.


It's returning the value of the expression count > 0. That's a Boolean expression (i.e. of type bool.)

It's like this:

bool result = (count > 0);
return result;

Another way of thinking of it (but please never write this code):

bool result = (count > 0) ? true : false;
return result;

or

bool result;
if (count > 0)
{
    result = true;
}
else
{
    result = false;
}
return result;

These are both ghastly contortions, but the important point is that count > 0 is just an expression of type bool. Boolean expressions are usually used in conditions (if, while etc) but they're just ordinary expressions which can be evaluated like any other expression.


false, that trusty old constant representing the opposite of true will be returned if count is not greater than zero.


you can rewrite the return statement like following :

if (count > 0)
            {return true;}
        else 
            {return false;}

if you return count, you would return an integer value, and the methods signature wouldn't match anymore


If the value of count is not greater than 0, it returns false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜