Use .Net event system : Event System « GUI Windows Forms « C# / CSharp Tutorial






using System;

public class SalaryEvent : EventArgs
{
  public string Message;

  public SalaryEvent(string message)
  {
    this.Message = message;
  }
}

public class Employee
{
  private int salary;

  public delegate void SalaryTaxEventHandler( object reactor, SalaryEvent myEvent );

  public event SalaryTaxEventHandler OnTax;

  public int Salary
  {
    set
    {
      salary = value;

      if (salary > 1000)
      {
        SalaryEvent myEvent = new SalaryEvent("Employee meltdown in progress!");
        OnTax(this, myEvent);
      }
    }
  }
}

public class EmployeeMonitor
{
  public EmployeeMonitor(Employee myEmployee)
  {
    myEmployee.OnTax += new Employee.SalaryTaxEventHandler(DisplayMessage);
  }

  public void DisplayMessage( object myEmployee, SalaryEvent myEvent )
  {
    Console.WriteLine(myEvent.Message);
  }
}


class MainClass
{
  public static void Main()
  {
    Employee myEmployee = new Employee();
    EmployeeMonitor myEmployeeMonitor = new EmployeeMonitor(myEmployee);

    myEmployee.Salary = 100;
    myEmployee.Salary = 500;
    myEmployee.Salary = 2000;
  }
}
Employee meltdown in progress!








23.63.Event System
23.63.1.Use .Net event system
23.63.2.Inference And Contravariance for Button Click, KeyPress, and MouseClick