Use Debug.Assert to find bugs in C#

The Debug class provides several methods for use in debugging code. The Assert method takes a Boolean (true or false) value and throws an exception if the value is false. A second parameter gives the error message that the exception should display. If an assertion fails while you are running in the debugger, you have the option of opening the debugger to the Debug.Assert statement that threw the exception.

Typically you use Debug.Assert to validate conditions such as input and output values in your code. For example, the following Average function uses Debug.Assert to validate the function's input parameter.

// Return the average of the numbers.
private float Average(float[] values)
{
Debug.Assert(values != null, "Values array cannot be null");
Debug.Assert(values.Length > 0, "Values array cannot be empty");
Debug.Assert(values.Length < 100, "Values array should not contain more than 100 items");

// If there are no values, return NaN.
if (values == null || values.Length < 1) return float.NaN;

// Calculate the average.
return values.Average();
}

Debug.Assert only works when you run a debug build. When you run a release build, Debug.Assert statements are ignored. This lets you flush out bugs during testing and then remove these statements from the final build.

To make this work, you need to ensure that the code can still work even if a Debug.Assert statement fails. In this example, the Average function does return a value even if the values array is null or contains no values.

To make a debug or release build, open the Build menu and select Configuration Manager. In the Active Solution Configuration dropdown, select Debug or Release and then rebuild the solution.

Finally, the Debug class is in the System.Diagnostics namespace, which is not included by default. To make using it easier, you may want to include the following line in your code.

using System.Diagnostics;

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.