Home   Cover Cover Cover Cover
 

Assert dialogs

Question: see book

The source code given for this exercise (with the previous exercise) contains a bug:
the constructor must, of course, have the same name as the class, thus changing

Test ()       to       Adder ()

The same applies to the object creation in the Main method:

new Test()       ->       new Adder ()

Answer: see 8.4.3 System.Diagnostics.Debug

The modified source code can look like this:

AdderExt2.cs
using System;
using System.Diagnostics;
using System.Windows.Forms;

class Adder : Form {
  TextBox amount = new TextBox();
  Button b = new Button();
  Label total = new Label();
  
  Adder () {
    amount.Left = 10; amount.Top = 10;
    Controls.Add(amount);
    
    b.Text = "ADD";
    b.Left = 10; b.Top = 40;
    b.Click += new EventHandler(Add);
    Controls.Add(b);
    
    total.Text = "0";
    total.Left = 10; total.Top = 70;
    Controls.Add(total);
  }

  void Add (object sender, EventArgs eargs) {
    try {
      int val = Convert.ToInt32(amount.Text);
      Debug.Assert(val >= 0, "Do not enter negative values");
      total.Text = (val + Convert.ToInt32(total.Text)).ToString();
    } catch (FormatException) {
      Debug.Assert(false, "Enter only numbers");
    }
  }
  
  public static void Main () { Application.Run(new Adder()); }
}