If I compile the following code snippet with Visual C# 2010 I ALWAYS get false:
object o = null;
Console.WriteLine("Is null: " + o == null); // returns false
Does anybody know why???
Comparing any variable with NULL will always evaluate to FALSE, regardless if it's value, unless IS NULL or IS NOT NULL is used. Violating this rule will affect the functionality of the code. The severity is critical which means that the code will not function correctly.
A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.
Why is easy; think of what you've written as actually being this:
object o = null;
Console.WriteLine(("Is null: " + o) == null); // returns false
It's testing "Is null: " + o
against null
, which will always be false
. This is due to the rules of operator precedence, where +
comes before ==
.
You should explicitly apply parens to make sure it's working like you want:
Console.WriteLine("Is null: " + (o == null)); // returns true
As noted in the comments by Jim Rhodes:
This is one of several reasons why you should ALWAYS use parentheses and never rely on compiler precedence rules.
I noted myself that I agree; that I don't even try to remember operator precedence rules myself, instead being explicit with parens all the time. I further suggest that this is also one reason to be very careful when relying on implicit type conversion and/or methods with multiple overloads.
I'd also like to point out that I really like something Ravadre noted in their answer; about why only "False" was printed, and not the whole text you were trying to print.
Operator precedence.
Try
Console.WriteLine("Is null: " + (o == null));
In your code, First o
is added to "Is null: "
string, which is then checked if it is null. Of course it isn't, so it is evaluated as false. Your call is the same as if you would just write
Console.WriteLine(false.ToString());
This is why only "False" is printed, even without your string.
The other answers have correctly diagnosed the problem: operator precedence is higher for concatenation than equality. What no one has addressed however is the more fundamental error in your program, which is that you are doing concatenation at all. A better way to write the code is:
Console.WriteLine("is null: {0}", obj == null);
Now there cannot possibly be an operator precedence problem because the expression in question only has a single operator.
In general you should avoid string concatenation, and favour string substitution, when performing output. It is easier to get it right, it is much more flexible, it is easier to localize programs written using this technique, and so on.
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