C# Assert Method

This C# example program uses the Debug.Assert method from System.Diagnostics.

Assert sends a strong message to the developer.

An assertion interrupts normal operation of the program but does not terminate the application. The Debug.Assert method in the System.Diagnostics class provides a way to implement this.

 

Example. We explore the Debug.Assert method in the C# language. We use Assert to catch a condition that should not occur and would be a bug if it did. This is not an exception. It will never occur in finished code.

 

Note: Debug calls are compiled out when in Release mode. Exceptions are always kept in the code.

Exception

C# program that uses Assert method

using System;
using System.Diagnostics;

static class Program
{
    static void Main()
    {
	int value = -1;
	// A.
	// If value is ever -1, then a dialog will be shown.
	Debug.Assert(value != -1, "Value must never be -1.");

	// B.
	// If you want to only write a line, use WriteLineIf.
	Debug.WriteLineIf(value == -1, "Value is -1.");
    }
}

Result
    A. The dialog is displayed.
    B. Message is written to the Output: Value is -1.

The second parameters to Debug.Assert and Debug.WriteLineIf are expressions. They will be evaluated by the runtime before being converted to a Boolean value (true or false) and then passed as a value to the methods themselves.

Then: The Debug.Assert method will be executed. It internally checks the value of this expression evaluation.

 

Discussion. There are more static methods on the Debug class in the System.Diagnostics namespace in the C# language. You can access these methods by typing "Debug" and pressing period in Visual Studio, which will display Intellisense.

Debug.WriteDebug.WriteLineIf, WriteIf

 

Overview: The Assert method is most disruptive, and other methods such as Debug.WriteLine are less of a burden to encounter.

 

 

 

Summary. Here we looked at an example of using the Debug.Assert method and an expression-based parameter to display an error condition to a developer of the program. We saw the error message displayed by Assert by a real C# program.