Friday, March 21, 2008

Sample of C# Debug.Assert() method.

Often we want to check something (input parameters of a method, external output, etc.) in debug mode (development and testing time) to control purposes, but we want to avoid additional overhead in release (production).

To solve the problem it is suggested to use method Debug.Assert.

For example, we want to control input parameter y of a method divide

static int divide(int x, int y)
{
Debug.Assert(y==0, "parameter y should not be zero");
return x/y;
}

Now, parameter will be checked and a message will be shown when value of y will be 0.





But in Release mode, the parameter y will not be checked and we avoid the additional overhead.

With help of reflector let's see compiled code in Debug and Release modes:

Debug mode





Release mode








Reference:

Assertions in Managed Code

1 comment:

Anonymous said...

Wouldn't that be:
Debug.Assert(y != 0, "parameter y should not be zero"); If you want to check for y=0?