Click here to Skip to main content
15,124,736 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The perfect way to create an if statement with negation is:
if (!myBool)
{
    Do();
}
I strive to write my code without smell and make it more readable. But I barely see the exclamation mark, so such code doesn't satisfy me.

What I have tried:

Although it will not be tolerated, I would like to write
if (myBool == false)
, because unlike others this line is more comfortable for me than previous one.

I do not need neither in
if (myBool == true)
, nor in
if (myBool != true)
, nor in
if ((myBool == false) == true)
, nor another mess. Only just
if (myBool == false)
to avoid an exclamation mark, but according to SonarLint it's not correct.
I also tried to use multiple ! like
if (!!!myBool)
It doesn't fit as well.

Additionally I tried those things:
if ( !myBool)
issue
if (! myBool)
issue

Is there a way to write more elegantly and preferably avoiding ! and without next?
bool myFalseBool = !myBool;
if (myFalseBool)
{
    Do();
}
May it be something like next
if not (myBool) // this example doesn't possible, though
{
    Do();
}
or maybe next?
public const bool NOT = false;
public const bool FALSE = false;

if (NOT == myBool)
{
    Do();
}

if (myBool == FALSE)
{
    Do();
}
What do you think? Have any ideas?
Posted
Updated 5-Oct-21 6:34am
v2
Comments
Richard MacCutchan 4-Oct-21 7:56am
   
What is wrong with:
if (myBool == false)

It makes the meaning clear.
RuthWa 4-Oct-21 21:28pm
   
I agree, it does (at least for me). But most of people will not, because https://rules.sonarsource.com/csharp/RSPEC-1125.
Richard MacCutchan 5-Oct-21 3:56am
   
I am not sure how 'official' that is, but either way it does not matter. What is important is that you code conforms to the rules of the language (i.e. the compiler accepts it), and is readable, especially to those who will maintain it in the future.
Richard Deeming 4-Oct-21 8:01am
   
Other options, depending on your C# compiler / language version:
if (myBool is false)
if (myBool is not true)
RuthWa 4-Oct-21 22:02pm
   
Cool, I've never seen that before. But is it right? Can you shortly explain what is it? Does it allowed to use such thing not only for nullable boolean, but both "bool" and "bool?" ?

It is probably the best answer.
Richard Deeming 5-Oct-21 3:46am
   
It's part of the C# pattern matching:
Pattern matching overview - C# guide | Microsoft Docs[^]

It will work with both bool and bool?/Nullable<bool> types.

The first one should work if you set your project's C# language level to 8. The second one requires a language level of 9. If you're targeting .NET Framework rather than .NET Core / .NET 5, you'll need to manually edit your project file to set the language level, and remember that some C# 8/9 features won't work:
Using C# 9 outside .NET 5 · Discussion #47701 · dotnet/roslyn · GitHub[^]
RuthWa 5-Oct-21 7:11am
   
That's incredible. Thanks a lot!
PIEBALDconsult 4-Oct-21 10:17am
   
if ( !mybool ) ...

In my humble opinion,
C#
if (myBool == false) 
//...

it is acceptable.


On the other hand, a better name for 'myBool' variable would be appreciated...
   
Comments
RuthWa 4-Oct-21 21:31pm
   
Maybe it is acceptable, but
https://rules.sonarsource.com/csharp/RSPEC-1125

So yes, the second option would be appreciated.
Another hat being thrown in the ring. I also like to avoid having exclamation marks (simply personal preference) in the conditions, but also accept that sometimes it's unavoidable. However in some situations consider how you can invert the boolean value before it reaches the condition.

Most of the time your booleans are going to be produced from inline condition statements and method invocations, so you can invert the value at those points.

For example:
C#
var idIsPositive = id > 0;
var accountExists = IsAccount(id);

if (!idIsPositive|| !accountExists) {
  // show an error
}

Could be:
C#
var idIsInvalid = id <= 0;
var accountIsMissing = !IsAccount(id);

if (idIsInvalid || accountIsMissing) {
  // show an error
}

Just make sure that you use really good naming conventions for your variables. Nothing is worse than reading code and the variables don't make sense in the context, even moreso than having reallyLongVariableNamesUnncessarily;
   
Comments
jsc42 4-Oct-21 9:33am
   
@Chris_Copeland's suggest is good!

If, for some reason (and I cannot think of any time that that is true), you cannot get a name that makes sense; or (as sometimes happens) you need to correct someone else's logic because they got the test the wrong way round, put the false test in parentheses e.g.

if (!(somethingFalse)) // Parentheses highlights the fact that something awkward is going on
doFalseAction;

alternatively, it is (just about) acceptable to do

if (condition)
{
// Nothing to do if condition is true
}
else // Condition is false
doFalseAction():

I have often seen

if (!condition)
doFalseAction();
else
doTrueAction();

If you come across that, invert the code to

if (condition)
doTrueAction();
else
doFalseAction();

Do not skimp on comments. If your code, after careful refactoring, is still not readable, alert the next reader that there is a pitfall to aviod e.g.

// Looking for a missing value
if (!(HasValue(thingBeingTested))) // See if thingBeingTested has not got a value
doNoValueAction(); // thingBeingTested has not got a value
To be honest, all your attempts at "getting round" what you see as a problem are ugly, inefficient, and unnecessary - and would almost certainly fail code reviews everywhere I've seen.
And make your code look "student grade" at the same time!

If you can't "see" the exclamation mark, then increase the font size of your IDE - "!" is quite large and visible compared to ".", ",", "^", and "~" for example, and missing any of them would make your code even harder to read.

C#
if (!int.TryParse(userInput, out qtyOfCheese))
   {
   ...
   }
Is pretty standard code!
   
v2
Readability with "if (! mybool)" statement in C#. Is there another way?

If really you can't read code with an '!', you will have big problems reading other's code and samples codes.
You can also try:
C#
if (myBool)
{
    DoTrue();
}
else
{
    DoFalse();
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900