Reputation: 9734
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???
Upvotes: 5
Views: 365
Reputation: 660159
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.
Upvotes: 8
Reputation: 40150
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.
Upvotes: 10
Reputation: 11957
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.
Upvotes: 11