Can .NET source code hard-code a debugging breakpoint?
You probably are after something like this:
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do something like this:
// Conditional("Debug") means that calls to DebugBreak will only be
// compiled when Debug is defined. DebugBreak will still be compiled
// even in release mode, but the #if eliminates the code within it.
// DebuggerHidden is so that, when the break happens, the call stack
// is at the caller rather than inside of DebugBreak.
[DebuggerHidden]
[Conditional("DEBUG")]
void DebugBreak()
{
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
}
Then add a call to it in your code.
System.Diagnostics.Debugger.Break
?
I ran into a situation once where this didn't work
System.Diagnostics.Debugger.Break();
but this did
System.Diagnostics.Debugger.Launch();
If you want to have only one line of code instead of 4, wrap
#if DEBUG
if (Debugger.IsAttached)
Debugger.Break();
#endif
into
public static class DebugHelper
{
[DebuggerHidden]
[Conditional("DEBUG")]
public static void Stop()
{
if (Debugger.IsAttached)
Debugger.Break();
}
}
and use
DebugHelper.Stop();
DebuggerHiddenAttribute
has been added to prevent the debugger from stopping on the inner code of the Stop
method and from stepping into the method with F11
.