Thursday 14 January 2016

Debugger.Break & its usage

Debugger.Break() is a very useful way to break the code in case you want to present an application demos with its source code without setting up breakpoints in the Visual Studio. However there is one small problem. What if this same application is launched from Visual Studio by pressing Ctrl+F5 instead of just F5?

Consider the below code:

static void Main(string[] args)
{
            Console.WriteLine("Start the program!");
            Debugger.Break();
            Console.WriteLine("End the program!");
            return;
}

If you press F5, it would break at line#2 in the function. And that is as per our expectations.

Now press Ctrl+F5. Surprise, you get an exception!!


This happens because you do not have a debugger attached to the program launched by pressing Ctrl+F5.

Simple Fix: Write a helper method and use that across code base instead of copying 6 lines everywhere :)

static void DebuggerBreak()
{
#if DEBUG
            if (Debugger.IsAttached)
            {
                Debugger.Break();
            }
#endif
}

static void Main(string[] args)
{
            Console.WriteLine("Start the program!");
            DebuggerBreak();
            Console.WriteLine("End the program!");
            return;
}