Home > .Net > Using Debug.Assert while writing .Net code

Using Debug.Assert while writing .Net code

Using Debug.Assert while writing .Net code

Today we have got new version of some product from other Team (component to retrieve data from DB). During our integration we have failed to run their code – got very strange errors ant etc.
Team which was responsible for this part of the project claimed that they checked everything and all functioning – but they did their tests only for Debug version of the Assemblies.

In .Net debug and release there shouldn’t be any difference in functionality Debug build version might be little bit slower. So we suspected in thread race problems and other weired stuff.

After several ours of debugging and phone calls with another team we have found the problem … it was really sad or funny to discover such simple mistake that developer can do.

See the following code:

public void DoSomething()
{

Debug.Assert(Foo());

}

public bool Foo()
{
//calculate something 
//set some data
}

command shown above is part of System.Diagnostics namespace useful for Debugging and making sure that code flow is working as designed by developer.
As you can see the problem in this code is that method called from Assertion. Very important not to call methods from Debuug.Assert this line of code will be removed by compiler during Release compilation.

The fixed code looks like this:
public void DoSomething()
{

bool res = Foo();

Debug.Assert(res);

}

public bool Foo()
{
//calculate something
//set some data

return sucsessFlag;

}
So the code flow doesn’t affected by the Assertion.
This looks small issue but believe me, very painful when it happening before version release :).

Categories: .Net Tags: ,
  1. No comments yet.
  1. No trackbacks yet.