Check if boolean is true? [closed]
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?
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
.
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)
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.
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 :)
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.
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.
精彩评论