Check if boolean is true? [closed]

Solution 1:

Almost everyone I've seen expressing an opinion prefers

if (foo)
{
}

Indeed, I've seen many people criticize the explicit comparison, and I may even have done so myself before now. I'd say the "short" style is idiomatic.

EDIT:

Note that this doesn't mean that line of code is always incorrect. Consider:

bool? maybeFoo = GetSomeNullableBooleanValue();
if (maybeFoo == true)
{
    ...
}

That will compile, but without the "== true" it won't, as there's no implicit conversion from bool? to bool.

Solution 2:

It depends on your situation.

I would say, if your bool has a good name, then:

if (control.IsEnabled)  // Read "If control is enabled."
{
}

would be preferred.

If, however, the variable has a not-so-obvious name, checking against true would be helpful in understanding the logic.

if (first == true)  // Read "If first is true."
{
}

Solution 3:

If you're going to opt for

if(foo == true)

why not go all the way and do

if(foo == true == true == true == true == true == true == true == true == true)

Which is the same thing.

I disagree that if its clearly named (ie: IsSomething) then its ok to not compare to true, but otherwise you should. If its in an if statement obviously it can be compared to true.

if(monday)

Is just as descriptive as

if(monday == true)

I also prefer the same standard for not:

if(!monday)

as opposed to

if(monday == false)

Solution 4:

The first example nearly always wins in my book:

if(foo)
{
}

It's shorter and more concise. Why add an extra check to something when it's absolutely not needed? Just wasting cycles...

I do agree, though, that sometimes the more verbose syntax makes things more readable (which is ultimately more important as long as performance is acceptable) in situations where variables are poorly named.