What does assert() method do

The use of assert statements can be an effective way to catch program logic errors at runtime, and yet they are easily filtered out of production code. An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it is not.

Assertion is a way of documenting your intentions and having the debugger inform you with a dialog if your intention is not met. It 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 functionality quickly. In a debug compilation, Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true .

When you implement Debug.Assert , make sure that any code inside Assert does not change the output of the program if Assert is removed. Otherwise, you might accidentally introduce a bug that only shows up in the Release version of your program. As shown in following example.

At first look we can say that above code will work properly and brake whenever condition become false. Here every time whenever "DecrementCounter" Counter is called then value of "cnt" will be decremented. When you build the Release version , this call to "DecrementCounter" is eliminated, so the "cnt" does not get updated. Eliminating Call to function will result to bug in the release environment. To avoid such error we can use temporary variable for comparison as shown below.

Assertions are especially useful in large, complicated programs and in high reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when code is modified, and so on. As a best coding practice try and avoid using function call inside the assert method.

Debug class and Trace class

The Systems.Diagnostics namespace includes Trace and Debug classes and both have very similar methods. The primary difference is that calls to the Debug class are typically only included in Debug build and Trace are included in Debug build and Release build. More about... Debug class and Trace class
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About