Code Trivia #6

It’s time for yet another code trivia and it’s business as usual. What will the following program output to the console?

using System;
using System.Drawing;
using System.Threading;

class Program
{
    [ThreadStatic]
    static Point Mark = new Point(1, 1);

    static void Main()
    {
        Thread.CurrentThread.Name = "A";

        MoveMarkUp();

        var helperThread = new Thread(MoveMarkUp) { Name = "B" };

        helperThread.Start();
        helperThread.Join();
    }

    static void MoveMarkUp()
    {
        Mark.Y++;

        Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, Mark);
    }
}

The output will be the following:

// A:{X=1,Y=2}
// B:{X=0,Y=1}

This is due to the fact that, as documented in ThreadStatic MSDN entry, initialization occurs in the class static constructor and therefore affects only one thread. The second thread will see the default value if it is a value type or a null reference if it is a reference type. In this specific case Point is a value type with the default value of {0, 0}.

2 thoughts on “Code Trivia #6”

    1. You are correct in the order in which the coordinates are printed, however, the values printed will differ between threads. I’ll update the post with the explanation.

Leave a comment