Is there any sort of style consensus on the following two coding styles? I'm more curious if this is the sort of thing where one is generally preferred in good code in C#, or if this the sort of thing that gets decided when picking a style for a coding project.
Style 1: Using the ! sign to indicate a not in a conditional
if (!myBool)
{
//Do Stuff...
}
Style 2: Using == false to indicate a check for falsehood in a conditional
if (myBool == false)
{
//Do Stuff...
}
Thanks!
To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!
Boolean Variables and Data Type ( or lack thereof in C ) C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.
FALSE are not boolean , they are Boolean . They are static instances of the two Boolean wrapper objects that correspond to the boolean values true and false . Boolean is similar to an enum . The TRUE and FALSE instances are the instances returned by Boolean.
The normal convention is
if (!myBool)
The one place where I don't go this route is with nullable booleans. In that case I will do
if (myBool == true)
{
}
Which is equivalent to
if (myBool.HasValue && myBool.Value)
I don't know of any language for which the latter is preferred. Use the former.
This indeed does what you expect, in most languages:
if (x == false)
...
But in e.g. C++, because true
is just a synonym for 1 (so 2
isn't true or false), this doesn't work:
if (x != true)
...
although it's fine in C#.
In fact, it can also get tricky in .NET -- you can trick a boolean to take an integer value, and mess it up with bitwise arithmetic (e.g. a & b
can be false when a
is 1 and b
is 2, even though both are "true").
In general, just use the former instead of worrying about boolean literals.
if(!myBool)
{
// Do Stuff here...
}
This is the preferred version, as since you already have a bool
variable that contains a true
or false
, there is no reason to do an additional evaluation in the if
statement.
Based on what aquinas has stated, this format is good to use unless you do have a nullable boolean (ex: bool? myBool
). If this is the case, use the former:
bool? myBool
if (myBool == false)
{
// Do stuff here...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With