[c#] Check if boolean is true?

bool foo = true;

// Do this?
if (foo)
{
}

// Or this?
if (foo == true)
{
}

I like one of them and my coworker the other. The result is the same, but what is (more) correct?

This question is related to c#

The answer is


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."
{
}

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)

Neither is "more correct". My personal preference is for the more concise form but either is fine. To me, life is too short to even think about arguing the toss over stuff like this.


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.


i personally would prefer

if(true == foo)
{
}

there is no chance for the ==/= mistype and i find it more expressive in terms of foo's type. But it is a very subjective question.


Both are correct.

You probably have some coding standard in your company - just see to follow it through. If you don't have - you should :)