Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Monday, October 20, 2008

Set a break point through code with C#

If you have spent time debugging, you probably know you can click any code line to add a break point. If you have spent some more time you have probably even figured out how to set conditional breakpoints, as Sara Ford explains in this "tip of the day".

But did you know you can also cause a break point to trigger from within your code? It is actually pretty easy using the Debugger class within the System.Diagnostics name space. I learned about the Debugger class while looking over the specifics for the "Debug and trace a .NET Framework application by using the System.Diagnostics namespace." section of the 70-536 exam.

If this code is run outside of the debugger, the OS will ask you if you would like to debug the process.

Debugger Break form Code Example

using System;

namespace BreakFromCodeExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Thing are going fine...");
Console.WriteLine("then something goes wrong and we want to break");
Console.WriteLine("so we can investigate further...");

//This is the call that fires the break point event
System.Diagnostics.Debugger.Break();

Console.WriteLine("You are now free to place break points with or without a GUI.");
}
}
}

Additional Resources
Debugger Class (Microsoft)
System.Diagnostics Namespace (Microsoft)

1 comment:

Anonymous said...

Hi, what do you think about Debugger.Launch(), is it better to use it instead of Break() in your sample?

To me it looks like Launch() is always better - because Break() looks for a running debugger and if it's not there, Launch() gets called anyway.

YMMV :)

Support This Site

LinkShare  Referral  Prg