Fast small quiz for sunny afternoon :
What is writing at the console those lines : ( please do not use a compiler) :
decimal? v = 100;
Console.WriteLine(v);
decimal? x = null;
x += v.Value;
Console.WriteLine(x);



#1 by pascanu at August 2nd, 2010
| Quote
100
100
#2 by tzup at August 2nd, 2010
| Quote
First WriteLine will print “100″. Second, I’d say also “100″, but I’m sure there’s a catch somewhere. I did run it on Snippet Compiler and there surely was a catch. Good quiz! Can you please post more quizzes Mr MVP ?
#3 by Alex Lazar at August 2nd, 2010
| Quote
Console.WriteLine(v); will output 100.00
Since {x += v.Value;} is equivalent to {x = x + v.Value;} and MSDN says that adding an instanced int? with a null int? will produce a null, I assume the same will happen to decimal? and so x is null
Console.WriteLine(x); will try to output a null so (as MSDN states) only the line terminator is written.
Didn’t use a compiler, but you didn’t say anything about the Internet
#4 by vim at August 2nd, 2010
| Quote
In your example:
v return 100 and x return nothing (it’s null)
For testing, we can use HasValue property, like this:
decimal? v = 100;
Console.WriteLine(v);
decimal? x = null;
if (x.HasValue)
{
x += v.Value;
Console.WriteLine(x);
}
else
{
Console.WriteLine(“x is null”);
}
#5 by Amit at August 2nd, 2010
| Quote
First WriteLine will print “100″ and the second should print null I guess
#6 by admin at August 4th, 2010
| Quote
Thank you for the answers. The idea was that this behaviour, although documented, is not obvious…