Assertions in C#

CsharpServer Side ProgrammingProgramming

Assert statements are an effective way to catch program logic errors at runtime. It has two arguments −

  • A boolean expression for a true condition, and
  • What to display in case of false.

Assertions are useful in large and complex programs to quickly flush out errors that generally arise when the code is modified. Avoid using any function call inside the assert method.

You need to be sure that whatever code you add inside an Assert should not change the output if it is removed. This is when you implement Debug. Assert in your program.

To implement it, you can use a temporary variable −

int temp= DecCounter(d);
Debug.Assert(temp !=0);

Above, the call to the counter will decrement the value. We have used the temp variable because Release Version eliminates the call when Assert is used. This can create a bug in the code, therefore better way is to use temp.

raja
Published on 24-Jul-2018 07:42:20
Advertisements