A Quick .NET Puzzle

Comments 0

Share to social media

Just a quick .NET puzzle.  Does this application ever throw that ApplicationException?  If so, why?


using System;
using System.Threading;

class Program
{
    static long Num = 0;

    static void Main(string[] args)
    {
        Thread t1 = new Thread(ModifyNum);
        t1.Start();
        while (true)
        {
            long k = Num;
            if (k != -1 && k != 0) throw new ApplicationException(
                "k is not -1 or 0.  It is " + k.ToString());
        }
    }

    static void ModifyNum()
    {
        while (true)
        {
            if (Num == -1) Num = 0;
            else Num = -1;
        }
    }
}

Stuck?  Then here's a hint: if you change Num from a long to an int, it never throws the exception.

Load comments

About the author

Jason Crease

See Profile

Jason Crease studied maths and computer Science at Cambridge University and joined Redgate several years ago as a Test Engineer. He specialised for some time in Testing .NET applications and was part of the team responsible for the development of ANTS Profiler and .NET Reflector. After working as a DevOps engineer supervising Redgate's own IT systems, he joined the DLM team, working on the practicalities of the management and automation of the application lifecycle.

Jason Crease's contributions