With numeric it is always same pretty:
if(a < 123) { ... } // disregards if `b` is `int?` or `int`
But with bool?:
bool? b = ...
if(b) { ... } // compiler error: can't convert bool? to bool.
There are following options:
if(b == false) { ... } // looks ugly, comparing bool? with bool
if(b.GetValueOrDefault()) { ... } // unclear when condition is true (one must know it's `false`)
if(b.GetValueOrDefault(true)) { ... } // required few seconds to understand inversion
I was curios whenever nullables (at least bool?) deserves this syntax to be used always:
if(b ?? false) { ... } // looks best to me
P.S.: this may looks like opinion-based question, but I didn't find similar to clear all my doubts alone... Perhaps some of those are best used in certain scenarios and I'd like to know in which ones.
The language designers had two choices, as far as allowing bool? to participate in control expressions of control statements requiring a bool:
Allow it, and make an arbitrary decision when it comes to null treatment
Disallow it, forcing you to make a decision each time it is relevant.
Note that the designers had much less of an issue with if(a < 123) statement, because "no" is a valid answer to questions "is null less than 123", "is null greater than 123", "is null equal to 123", and so on.
The if (b ?? false) and if (b ?? true) are very convenient constructs, which let you explain to the readers of your code and to the compiler in which way you wish to treat nulls stored in a bool? variable.
Every time I see someone using a nullable boolean bool?, I ask them why. Usually, the answer is -- "well, I'm not really sure". It is effectively creating a three state condition which in my opinion makes the code harder to read regardless. What does null mean, if it is always false then why bother with making it nullable in the first place?
But to answer your question more directly, I prefer the
if (b ?? false)
syntax over the
if (b.GetValueOrDefault())
Some years later and from personal experience I can tell that following syntax is clearly a winner:
if(b == false) { /* do something if false */ }
if(b == true) { /* do something if true */ }
if(b != false) { /* do something if NOT false, means true or null */ }
if(b != true) { /* do something if NOT true, means false or null */ }
What I thought as "ugly" turns out to be the easiest to understand.
== vs ??
Nullables are often results of linq queries and using ?? add unnecessary layer of complexity to understand the condition.
Compare
if(Items?.Any(o => o.IsSelected) == true)
vs
if(Items?.Any(o => o.IsSelected) ?? false)
The first one is much easier to read, it's a simple check if any item is selected.
When my (probably untrained?) mind reads the latter, I have to make a mental full stop at ??, do inversion and only then I understand when if block will be executed. With ?? I am likely to make a mistake when quickly looking throught the code written by someone else or even my own code given enough time has passed.
Related
I have a DataGridView cell that is of type System.Single.
if (myDataGridView.Rows[0].Cells[1].Value == null)
{
//some code
}
myDataGridView.Rows[0].Cells[1].Value has value {}. It's not null, nor is it 0, what should be on the right hand side of == to make the conditional true?
It's something called DBNull.Value as stated before you can use it:
if (myDataGridView.Rows[0].Cells[1].Value == DBNull.Value)
{
//some code
}
As noted, the value is an instance of DbNull.
Given that DbNull.Value is a singleton (and thus safe for reference comparisons), two options come to mind:
if (myDataGridView.Rows[0].Cells[1].Value == DBNull.Value)
or
if (myDataGridView.Rows[0].Cells[1].Value is DbNull)
Personally I quite like that latter - it fits in with the "is null" approach within a database, and it reads well... it makes it clearer that I'm interested in nullity as a sort of property rather than performing an actual equality comparison.
Have you tried this?
if (DBNull.Value.Equals(myDataGridView.Rows[0].Cells[1].Value))
{
//some code
}
I have a slight problem when working with c# and using IF statments with multiple conditions.
This is the most common occurance.
private void SomeFunction(string SomeString)
{
if(SomeString != null && SomeString.Trim() != "")
{
}
}
In some languages like javascript if the first argument fails (SomeString != null) the second check wont be made. C# seems to check both arguments even if the first one fails and then the second one will throw an exception since you cannot use .Trim() on a null value.
Right now I am going over this by nesting my ifs which is messy work. Like this:
private void SomeFunction(string SomeString)
{
if(SomeString != null)
{
if(SomeString.Trim() != "")
{
.....
}
}
}
Does anybody have any suggestions or best practices on a better way to solve this?
C# seems to check both arguments even if the first one fails
That's not true, see && Operator (C# Reference) in MSDN.
Your assumption is totally wrong. When you use the conditional AND if the first condition is FALSE the second condition is never evaluated or executed. In the conditional OR if the first condition is TRUE the second one is never evaluated or executed.
In other words, if the compiler has enough info to determine the result of the expression it stops to consider the second part of the expression.
This is known as short-circuit evaluation.
It is a basic programming principle for C derived languages but also for every other major language.
There is a better way:
private void SomeFunction(string SomeString)
{
if (!string.IsNullOrWhiteSpace(SomeString))
{
// your code
}
}
if (!String.IsNullOrEmpty(SomeString))
{
}
if(!string.IsNullOrEmpty(SomeString))
similar to ProgramFOX prefer this if you insist on doing ".Trim()"
Is there any difference between below two statements
if (null != obj)
and
if (obj != null)
If both treated same which will be preferable?
The first is a Yoda condition. Use it you should not.
The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.
However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.
Consider this:
public class TestClass
{
...
public static bool operator !=(TestClass left, TestClass right)
{
return !left.Equals(right);
}
}
In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.
So to summarize:
The code generated is different
The performance and end results should be the same
Except when you have broken code in the type involved
Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:
if (null == obj)
Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:
if (obj = null)
This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:
if (null = obj)
No, but the second way is more common and more readable (and more logical in my opinion)
No, there is not. It's exactly the same.
The style null == obj is sometimes just used to prevent the common typo obj = null to not accidently assign null to a variable, but with != there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null.
So the compiler prevents you from accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.
They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null) // should be obj == null
But of course this doesn't apply to the != operator, so in your example it's just a difference of style.
First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:
if (5) { } // true
if (0) { } // false
Sometimes it created problems if you forgot to type one '=' char:
if (x = 5) { } // this was true always and changed x value
if (x == 5) { } // this was true, if x was equal to 5
So, Yoda syntax was used, to receive compiler error in case one '=' was missed:
if (5 = x) { } // this was generating compiler error for absent-minded programmers
if (5 == x) { } // this was true, if x was equal to 5
C# allow only boolean value in conditions, So
if (x = 5) { } // this won't compile
if (x == 5) { } // this is true, if x was equal to 5
What about boolean types?
if (y = true) { }
if (y == true) { }
Well, this is useless code, because you can just write if (y).
Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.
The use of the first form
if (blah == obj)
stems from the days when compilers would not catch if (obj = blah) i.e. unintentional assignment, unless compile warning level was set to maximum
this is related to comparing values in C#.
basically by default, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks
This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null or non-0 would be treated as true, otherwise it was equivalent to false. This meant that any assignation of a constant would always be true.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5 is the result of 2+3, myInt = 5 also returns 5.
Because of this, it was recommended that you check the variable against the constant. The null example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i is assigned the value of 1, which then returns the value of the assignment, 1, to the if statement. This is equivalent to true, and the if condition matches.
If you were to attempt to assign i to the constant 1, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }, as a string has... two ... default values from a semantic perspective.
Reverse comparison protects you from errors, when you use == (compare) instead of = (assign). But complier also warns you if you do this.
Hello I was thinking of what is better to write (in matter of speed and/or efficiency):
bool Method(...) { ... }
...
bool result = Method(...);
if (result == false)
{ ... }
// or
if (!result)
{ ... }
Or, alternatively...
if (result == true)
// or
if (result)
I'm asking because I use first one (result == false) but sometimes it gets very long, especially in condition ? expr : expr statements.
Personally, I cringe whenever I see something like result == false. It's a rather nasty misuse of the equality operator in my opinion, and totally unnecessary. While I'd imagine the compiler should turn the two expressions into the same byte code, you definitely want to be using !result. Indeed, it is not only the more direct and logical expression, but as you mention, makes the code a good deal shorter and more readable. I think the vast majority of C# coders would agree with me on this point.
Runtime speed is the same - both snippets compile to the same MSIL code representation.
Using (result == false) instead of (!result) feels kinda sloppy though.
There is no performance difference in runtime code. Most of the coding-guidelines in the companies i worked prefer !result.
I don't think there is any difference, and if there is you would probably have a hard time measuring it. Any difference is likely to be in the noise of the measurement.
You should definitely use the expression with the ! operator, not because it's faster but because it's safer.
If you accidentally use one equals sign instead of two, you assign the value to the variable instead of comparing the values:
if (result = false) {
For other data types the compiler can catch this, as an expression like (id = 42) has an integer value so it can't be used in the if statement, but an expression like (result = false) has a boolean value so the compiler has to accept it.
(An old C trick is to put the literal first so that it can't be an assignment, but that is less readable so the ! operator is a better alternative.)
I think there are three steps in this process. First, you believe that there should always be a comparison inside an if, so you write if(this.isMonkey == true) banana.eat();
Or, more realistically
if(SpeciesSupervisor.getInstance().findsSimilarTo(Monkey.class, 2) == true) {
String f = new PropertyBundle("bananarepo").getField("banana store");
EntitiyManager.find(Banana.class,f).getBananas().get(1).eat();
}
Then, you learn that it is fine to ask if(this.isMonkey) and that this formatting allows better reading as a sentence in this example ("if this is a monkey").
But at last, you get old and you learn that if(b) is not very readable, and that if(b==true) gives your poor brain some clue what is happening here, and that all these harsh claims of "misuse", "abuse", yada yada, are all a little overstated.
And as for the performance. In Java it would not make a shred of difference. I don't think .NET is so much worse. This is the easiest optimization a compiler could do, I would bet some money that the performance is the same.
Cheers,
Niko
Although I agree with #Noldorin that if(!result) is to be preferred, I find that if(result == false) and its ilk are very useful if you have to test a nullable bool, which most frequently happens in data access scenarios.
Edit: Here's a sample program that explains the different ways you can use the equality operator on a nullable bool.
class Program
{
static void Main(string[] args)
{
TestNullBool(true);
TestNullBool(false);
TestNullBool(null);
Console.ReadKey();
}
private static void TestNullBool(bool? result)
{
if (result == null)
{
Console.WriteLine("Result is null");
}
if (result == false)
{
Console.WriteLine("Result is false");
}
if (result == true)
{
Console.WriteLine("Result is true");
}
}
}
/* Output:
Result is true
Result is false
Result is null
*/