Jungle Coder
🦞🦞🦞🦞🦞🦞
Just added post themes! Witness The Colors, and Exult!

A .NET breakpoint that only breaks if a debugger is attached

This is a helpful little function that I wrote when I found out about the [System.Diagnostics.Debugger.IsAttached](https://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached(v=vs.110\).aspx) property. I found it useful for debugging a synchronization service that I was working on at work.

What other little utilities like this have you made?

public static class utils {
    public static void DebugIf(Func<bool> toCheck)
    {
        if (System.Diagnostics.Debugger.IsAttached && toCheck())
        {
            System.Diagnostics.Debugger.Break();
        }
    }
}

Usage:

using System;

class App {
    public void Main(string[] args) {
        // Fires the debugger if one is attached,
        // and if we passed a flag asking for debugging
        utils.DebugIf(() => args.Length > 0 
                            && args[0] == "--debug");
    }    
}

Comments

Previously: Academic Portfolio
Next: Make sure you're able to run timer based services on demand