Assert Yourself
The .NET framework provides a Debug class to help debug your code. One of the most powerful methods in this class is Assert. This method is static and returns void in C#, and is a shared sub in VB.NET.
An Assert statement both documents what you believe is happening in your code at any given moment and forces an error and notification if that assumption is incorrect.
.NET provides both a Debug.Assert statement and a Trace.Assert method. Debug methods are removed from your code in release mode, but Trace methods are not (or can be toggled on and off from configuration files (see Chapter 22).
You can see a good (if contrived) use of the Assert statement by adding a third menu choice, "menuTestDivsion," whose event handler is shown here:
private void menuTestDivision_Click(
object sender, System.EventArgs e)
{
Employee joe = new Employee("Joe",47,5);
Double pctgOfLife = joe.Age / joe.YearsOfService;
lblDisplay.Text =
joe.Name +
" has worked here for " +
pctgOfLife + "% of his life!";
}When you run this code and choose the Test Division menu choice, you learn that Joe has worked at the company for 9 percent of his life. What happens, however, if the value passed in as years of service is 0. You will then divide 47 by 0, which is illegal, and your program will crash.
The right approach is to test for zero years of service, and if it is found, to skip the division. Assume ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access