views:

300

answers:

6

In C#, can you use a boolean predicate on its own as the parameter for an if statement?

eg:

string str = "HELLO";
if (str.Equals("HELLO"))
{
    Console.WriteLine("HELLO");
}

Will this code output "HELLO", or does it need to be:

string str = "HELLO";
if (str.Equals("HELLO") == true)
{
    Console.WriteLine("HELLO");
}

If there is anything else wrong with the above code segments, please point it out.

EDIT: double equals as per answers

+4  A: 

Well, the latter snippet won't even compile because it's trying to assign true to str.Equals("Hello") (you've got a single = instead of ==) but either:

if (str.Equals("HELLO"))

or

if (str.Equals("HELLO") == true)

will work. The latter is pretty strongly discouraged though - it's pretty ugly.

Bear in mind that string overloads ==, so you can actually write:

if (str == "HELLO")

which is somewhat simpler.

Jon Skeet
Just to expand on Jon's response a little, the if statement will operate with any expression that evaluates to a boolean result.
Lazarus
If I am experiencing results contrary to this answer, what could be going wrong? Could there be an issue with string terminating characters or something else?
Craig Johnston
you could always try str.Trim() == "HELLO" to ensure any whitespace is removed from the beginning and end your string.
derek
+2  A: 

Yes you can.

(Your second example needs 2 = (i.e. ==) to be correct).

ck
This is the chosen answer because it was earliest.
Craig Johnston
+3  A: 

The second version won't even compile, since you need ==, not =.

Seeing code like if (foo == true) makes bile rise up into my mouth.

Marcelo Cantos
If `foo` is a nullable boolean, `foo == true` is a valid option.
Jens
(foo == true != false) evaluates to the same result, but your fellow developers won't invite you to their parties anymore.
Jono
Jens, I never said it was invalid.
Marcelo Cantos
+2  A: 

The code you have is correct, the if statement checks to see if the statement within the brackets evaluates to true.

Remember that comparisons in c# use == not = , so it should be if (x == true)

This can be used in other situations like:

bool isACat = true;

if (isACat)
{
}

It is good practice to put is or a similar identifier (Is/Has/Should/Will/Do/Must...) before boolean variable names, as it makes it easy to read when you are not using == true.

SLC
You don't always need an `is` prefix. Anything that semantically can be either "yes" or "no" is appropriate.
Will Vousden
You don't need it, but it is a good practice, rather than have if (cat)
SLC
@SLC: I mean that there are other semantically correct identifier names that don't have an `is` prefix. For example, `hasSomeProperty`, or any verb-noun pair where the verb is in the third person simple present tense (as opposed to imperative, for method names). I suppose more complicated names only really work for object properties, though, where there's a clear subject.
Will Vousden
@Will has is just a rephrasing of is, isFourLegged or hasFourLegs... the key point is that it should be recognisable as a boolean.
SLC
@SLC: Sure but what about something like `hasCar`? `isInPossessionOfCar`? Or what about `SomeType.AcceptsConnections`, which is `true` if objects of `SomeType` accept connections? I'm just saying that sometimes `is` isn't the appropriate verb!
Will Vousden
@Will Yes, sometimes it isn't, all I am saying is, make sure they are instantly identifiable as boolean. In most cases, putting Is/Has/Should/Will/Do/Must/etc. in front makes it much clearer, and many programming guides recommend you do so. Compare selected with isSelected, Complete with isComplete, etc.
SLC
@SLC: I fully agree that `isSelected` is better than `selected`, I'm just talking about which verb is used as a prefix, that's all :) All of those examples you just gave are exactly what I was trying to demonstrate.
Will Vousden
@Will then we are in agreement :)
SLC
+2  A: 

can you use a boolean predicate on its own as the parameter for an if statement

Strictly speaking, the answer to this is 'no', because a predicate is a function (in the mathematical sense). What you can use for the conditional expression in an if is any boolean expression, including (as here) the result of the invocation of a predicate on a value.

To expand, the 'predicate' here is 'equals HELLO'. It is a function (in the mathematical sense) that operates on values of type string, and returns boolean values. Once you have obtained a boolean value (by applying this function to a particular string, str), you do not need to explicitly compare it to true: you can just use it.

As you will see from others' answers, code in which expressions of boolean type are explicitly compared to boolean literals will often cause code-style pain in the reader :) (My 'favourite' peeve is <boolean expression> ? true : false).

AakashM
Isn't the isEquals() a function?
Craig Johnston
@Craig Johnston : yes, 'is equals' is a function that consumes *two* values and returns a boolean. By specifying one of those values in advance, we make a predicate, a function which consumes *one* value and returns a boolean.
AakashM
Why do you say isEquals is a function that consumes two values? It consumes only one value: the string parameter.
Craig Johnston
@Craig Johnston : no, 'equals' takes two parameters (the two items to compare for equality). 'equals HELLO' is however a *different* function, which takes only one parameter. Since it is a function that takes one parameters and returns a boolean, it is a predicate. You could call it a 'partial application' of 'equals' if you wanted to use the technical term.
AakashM
A: 

There's nothing wrong.

Just two different ways of picking up the same spoon to feed yourself ;)

MasterGaurav