Trace.Assert Method (Boolean)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Checks for a condition; if the condition is false, displays a message box that shows the call stack.

Namespace:   System.Diagnostics
Assembly:  System (in System.dll)

public static void Assert(
	bool condition


Type: System.Boolean

The conditional expression to evaluate. If the condition is true, a failure message is not sent and the message box is not displayed.

Use the Trace.Assert method if you want to do assertions in release builds. The Debug.Assert method works only in debug builds. For more information, see Assertions in Managed Code.

Typically, the Assert(Boolean) method is used to identify logic errors during program development. Assert(Boolean) evaluates the condition. If the result is false, it sends a failure message to the Listeners collection. You can customize this behavior by adding a TraceListener to, or removing one from, the Listeners collection.

When the application runs in user-interface mode, it displays a message box that shows the call stack with file and line numbers. The message box contains three buttons: Abort, Retry, and Ignore. Clicking the Abort button terminates the application. Clicking Retry sends you to the code in the debugger if your application is running in a debugger, or offers to open a debugger if it is not. Clicking Ignore continues with the next instruction in the code.


The display of the message box depends on the presence of the DefaultTraceListener. If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. The DefaultTraceListener can be removed by the <clear> Element for <listeners> for <trace>, the <remove> Element for <listeners> for <trace>, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).

You can change the behavior of the DefaultTraceListener in the configuration file that corresponds to the name of your application. In this file, you can enable and disable the assert message box or set the DefaultTraceListener.LogFileName property. The configuration file should be formatted as follows:

      <add name="mySwitch" value="4"/>
    <trace autoflush="false" indentsize="4"/>
    <assert assertuienabled="true" logfilename=".\TraceLog.txt"/>

The following example creates an index for an array. Then some action is performed that sets the value of the index. Next the code calls Assert to verify the index value is valid. If it is not valid, the Assert outputs the call stack.

// Create an index for an array.
 protected int index;

 protected void Method()
 // Perform some action that sets the index.

 // Test that the index value is valid. 
 Trace.Assert(index > -1);

.NET Framework
Available since 1.1
Return to top