Debug.Assert in C# is your friend

Jul 18, 2014

For all those important methods of your application where you would like to / have check an input parameter or output result for null / empty check.

In case you don't want those checks while you release and only want them to be break into debug or pause while debugging - Debug.Assert is your friend.

Let say we have a method that takes string as input:

private void SomeMethodAbc(string someInput)
{
    //// TODO: Doing something in here !!
}

What you want is to validate that someInput is not null, empty or whitespace. But you know your input well and sure that it won't be null, empty or whitespace in production.

So in that case you just require this check for debug or development purpose.

You can use Debug class from System.Diagnostics and its method Assert to achieve that.

When you add a Debug.Assert and the provided condition evaluate to false - you will be prompted with a message box that displays output message provided and call stack where this incident happens. Something similar to this:

Debug.Assert Demo Sample

Code for using Debug.Assert

private static void SomeMethodAbc(string someInput)
{
    Debug.Assert(!string.IsNullOrWhiteSpace(someInput), "Hey, did you just passed null or something to me??");
}