Welcome to RightHand's community place Sign in | | Help

Can you spot the problem?

Check out this code:

static void Main(string[] args) { string test = null; Console.WriteLine("Is test null: " + test == null); Console.ReadLine(); }

And guess the output without running the code.

Published 28. junij 2007 13:16 by Miha Markic
Filed under:

Comments

# re: Can you spot the problem?

28. junij 2007 14:14 by Josh
Can you explain that outcome. I guess wrongly true. Interested in hearing your feedback.

# foreachDev » Testing for Null

28. junij 2007 14:28 by foreachDev » Testing for Null

# foreachDev » Testing for Null

28. junij 2007 14:28 by foreachDev » Testing for Null
PingBack from http://foreachdev.net/blog/2007/06/28/testing-for-null-2/

# re: Can you spot the problem?

28. junij 2007 14:37 by Giuseppe
i guess "false" because the first step is to concat "is test null:" + test --> "is test null: and after the concatination the string will be compared to null --> false

# re: Can you spot the problem?

28. junij 2007 15:40 by Miha Markic

Hi Josh,

Giuseppe is correct. The order of operators is misleading in this case. As a human you know what you want to achieve and it seems logical that it will work, but the operator precedence is not what you would think. :-) + has a precedence over ==.

One can find the operator precedence order here:

http://msdn2.microsoft.com/en-us/library/6a71f45d(VS.80).aspx

# foreachDev » Implicit Casting is evil

# re: Can you spot the problem?

29. junij 2007 14:04 by Giuseppe
i have a good riddle as well (T-SQL): SELECT DATEADD(MONTH, 1 , '20070131')
Anonymous comments are disabled