C# quiz
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);
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);
100
100
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 ?
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
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”);
}
First WriteLine will print “100″ and the second should print null I guess
Thank you for the answers. The idea was that this behaviour, although documented, is not obvious…
100
null