Testing a null reference always returns false ... even when null

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 anyone know why ???

+5
source share
3 answers

Why is it easy; think about what you wrote, as a matter of fact:

object o = null;
Console.WriteLine(("Is null: " + o) == null); // returns false

Testing "Is null: " + oagainst null, which always will be false. This is due to the operator precedence rules where +preceded ==.

You must explicitly apply parens to make sure that it works the way you want:

Console.WriteLine("Is null: " + (o == null)); // returns true

As noted in the comments of Jim Rhodes :

, .

, ; , parens . , , / .

, - Ravadre ; , "False", , .

+10

.

Try

Console.WriteLine("Is null: " + (o == null));

o "Is null: ", , . , , . ,

Console.WriteLine(false.ToString());

"False", .

+11

: , . , , . :

Console.WriteLine("is null: {0}", obj == null);

, .

, . , , , , ..

+8
source

All Articles