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);

Posted

in

by

Tags:

Comments

7 responses to “C# quiz”

  1. pascanu Avatar
    pascanu

    100
    100

  2. tzup Avatar
    tzup

    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. Alex Lazar Avatar

    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. vim Avatar

    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. Amit Avatar

    First WriteLine will print “100″ and the second should print null I guess

  6. admin Avatar
    admin

    Thank you for the answers. The idea was that this behaviour, although documented, is not obvious…

  7. smita Avatar
    smita

    100
    null

Leave a Reply

Your email address will not be published. Required fields are marked *