Which is clearer form: if(!value) or if(flag == value)?

C#Not Operator

C# Problem Overview


I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preference for one form over the other.

Obviously, the best answer is "refactor the code so you don't need to test for falsehood" but sometimes there's no easy way to do so and the "else" branch is simply to continue processing. So when you must have an "if not false" construct, which is the preferred standard:

The not operator

if (!value)

Or the test for false

if (value == false)

C# Solutions


Solution 1 - C#

if (!value) is easier/faster to follow. Subjective as you said. As long as you are consistent, this is the main thing.

EDIT

One other point to add - omitting the true/false keywords should also (hopefully) force the coder to use better named variables. Bool variables should always indicate meaning or state purpose, such as:

if (MyWallet.IsEmpty)

There is no reason with the above to use == false or == true as it's redundant. The above is human readable immediately.

Far better than having to decipher:

if (MyWallet.EmptyStatus == true) or something ridiculous like this.

Solution 2 - C#

I personally like

if ((value == false) == true) ...

cause this is verifying that the statement value is false is actually evaluating to a boolean true...

and, then, obviously, covering both posssibilites adds even more clarity,

if ((value == false) == true && (value == false) != false)

<grin/>

and for those of you who are real gluttons for clarity, and demand incontrovertible readability, I'd suggest

if (((value == false) == true && (value == false) != false) == true)

But seriously, and I just thought of adding this, creating appropriate and meaningful variable Names is the key to this issue. You can easily, in the class where value is declared, add a computed variable as in (say "value "is actually "LaunchMissile"),
public bool AbortLaunch => !LaunchMissile,
then all you need is
if (AbortLaunch) ...,
and then it is terse, eminently readable, and avoids the negation operator.

Solution 3 - C#

if (!value)

This is always clearer in my opinion.

if (value == false)

I hate to say this, because it sounds kind of mean, but this normally shows that the person writing the code doesn't really understand the use of boolean values. You don't need to re-validate what a boolean is in an if statement. It's redundant.

(Personally, I would be annoyed at the person too if they named the variable value instead of something more meaningful. I have a feeling what you posted is just psuedo code, I would definitely ding that on a review.)

Edit (in response to a comment below):

It may look trivial, but often it is a sign of much bigger things. Truthfully, most people who do use var == true etc. don't understand. It's just a fact. I'm not saying their stupid or they shouldn't be programmers just that there is probably something that they need to review and learn. The problem is that when logic gets much more complex, not understanding concepts like this can lead to much much bigger problems down the road. Some people say "it's a style." That's fine. The real question in this case is, "How is it beneficial for me to do it this way? What do I or other people get from it?" If you can't solidly answer that question, then you need to ask yourself "Why is this a good idea?"

Solution 4 - C#

I would never use if(value == true), so just for consistency I would also not use if(value != false).

Solution 5 - C#

if(!value) is clearer and more "elegant", specially if you name boolean variables correctly

  • isWhatever
  • hasWhatever
  • etc

Something like

if (Page.IsPostback == true)

seems redundant to me

Solution 6 - C#

Dissenting opinion (kind of)

From a compilation standpoint, you're going to get the same IL, so it really only matters from a readability standpoint.

From that standpoint, the if(value == false) is more obvious to a casual reader, and there is less chance of missing the ! before the bool.

Honestly, I use both approaches, and most times, I make it depend on my variable name. If it still sounds ok to say "not" in place of the "bang", I'm likely to use the bang notation

e.g.

if(!gotValue) {}
//if (I've) not gotValue

//but

if(checkValue == false){}
//If (I've) not checkValue doesn't quite work here grammatically.

Solution 7 - C#

I use Not value when coding in VB but tend to use value == false when coding in C#. I find that the exclamation point can sometimes be lost in the name of the variable (e.g. !legal). Maybe it's because I'm, uh, a seasoned veteran.

Solution 8 - C#

I would favor using if(!value) because, depending on the names of the variables involved, the "true" case makes much more sense according to English semantics.

Consider one of the examples in this MSDN article:

if(pane.IsChecked)

reads in English as, "If the pane is checked".

However, if(pane.IsChecked == true) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.

One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "== true" makes this example more readable, and MSDN doesn't think so either.

Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.

Solution 9 - C#

I would normally prefer if (!value) too, when I know for sure that value is a boolean. But many times it can be a string, or a number.

The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).

Rant over. My suggestion: be explicit, especially if your language is the “very dynamic” type (i.e. JavaScript, PHP, Perl).

Solution 10 - C#

Whatever one you prefer. Pick one and stick to it.

Solution 11 - C#

I am sorry to say, the second just looks stupid to me.

I'd add an extra level, if someone prefers it:

if( (value==false) == true )

:)

Solution 12 - C#

I don't think it's all that subjective. I have never seen it recommended in the longer form. Actually all the books and coding guides and "How to be a good programmer" HowTos I've read discourage it.

It falls in the same category as

if (value) {
  return true;
} else {
  return false;
}

OTOH, all the answers given here make my first statement kinda equal not true.

Solution 13 - C#

I favour the if (!value) style at least for evaluating variables or common properties like Page.IsPostback and the like. For anything more complex I tend to parenthesise the expression like thus:

if (!(SomeType.SomeProperty.CallingAMethod(input).GetSomething.BooleanProperty))

Just to draw a little more attention to it.

All in all, it's an argument for Perl-style unless and until keywords.

Solution 14 - C#

If the condition is just a check of a single value, then !value is quicker.

However, when the condition contains multiple value checks, I find it much easier to read value == false. Somehow it is easier to parse multiple checks for equality than multiple negations of values.

Solution 15 - C#

I actually many of forms possible.

This is not actually how it is written to standards, but this is how I see it:

//if foo is(or exists)
if(foo)

//if foo is true
if(foo == true)

//if foo doesn’t exist
if(!foo)

if foo is false
if(foo == false)

Hence I don’t see == false is redundant.

Solution 16 - C#

I prefer the second option, the if (value == false) one. I gladly use if (~value) or if (not value) in languages that support it, but that ! just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.

Also, two things:

  1. I never do if (value == true), and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky ! is simply worse.
  2. I think it's really a matter of personal taste, just like the brace-on-a-newline debate. I would never criticize a teammate for silly little things like that, and I have a hard time understanding the people who will.

Solution 17 - C#

Whatever condition an if block should evaluate in order to execute must evaluate to true.

Hence, when value is false, the reason why if (!value) allows an if block to execute is because the ! operator essentially flips the false value of value to true, thus making the resultant condition within the parentheses evaluate into a true one that an if block needs in order to execute.

if (value), if (!value), if (flag == value), if (value == true), if (value == false), depending on what's to be achieved, are valid code. E.g. if (value == true) is very useful when value is a nullable boolean, because if (value) will give a syntax error, and if (value.Value == true) will throw exception if you didn't ensure that value is not null before the if block is executed.

Solution 18 - C#

I am also of the opinion that using == inside an if is redundant and I have another suggestion, at least visually, by introducing spaces:

if ( ! created)

Even using OpenDyslexic as font, the not sign ! next to the opening bracket ( can be too close to distinguish it at a glance if(!created).

Solution 19 - C#

I use if (value == false) The ! in if (!value) is so small I sometimes miss it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodexArcanumView Question on Stackoverflow
Solution 1 - C#KP.View Answer on Stackoverflow
Solution 2 - C#Charles BretanaView Answer on Stackoverflow
Solution 3 - C#kemiller2002View Answer on Stackoverflow
Solution 4 - C#Bill the LizardView Answer on Stackoverflow
Solution 5 - C#Claudio RediView Answer on Stackoverflow
Solution 6 - C#RobaticusView Answer on Stackoverflow
Solution 7 - C#Rob WindsorView Answer on Stackoverflow
Solution 8 - C#DavidView Answer on Stackoverflow
Solution 9 - C#mishooView Answer on Stackoverflow
Solution 10 - C#IVladView Answer on Stackoverflow
Solution 11 - C#Pavel RadzivilovskyView Answer on Stackoverflow
Solution 12 - C#LucView Answer on Stackoverflow
Solution 13 - C#Quick Joe SmithView Answer on Stackoverflow
Solution 14 - C#CorinView Answer on Stackoverflow
Solution 15 - C#SmarView Answer on Stackoverflow
Solution 16 - C#OakView Answer on Stackoverflow
Solution 17 - C#OlumideView Answer on Stackoverflow
Solution 18 - C#PatxisteinView Answer on Stackoverflow
Solution 19 - C#user1312568View Answer on Stackoverflow