Events/Delegates example in C#


I made a little events/delegates example. I'm sharing it with you because events and delegates can be hard when your learn them and this example could help you.

I know, there's better way to divide, but I needed a subject for the example. So I took the division.

You can download the example, it's a windows forms application with 2 textboxes and 1 button.

You enter 2 numbers in the textboxes and you click on the button and it will show the result or show an error.

Divison class (Division.cs) :

class Division
{
  public delegate void EventHandler(Object sender, DivisionEventArgs e); //Delegate
  public event EventHandler DivisionDone; //This event will be executed when the divison will be done.
  public event EventHandler DivisionPerZero; //This event will be executed when the divisor is 0.

  public Division() //Constructor
  {
  }

  public void Divide(int dividend, int divisor)
  {
    if (divisor == 0)
    {
      if (DivisionPerZero != null)
      {
        DivisionPerZero(this, new DivisionEventArgs(dividend, divisor, 0.0)); //Execute the DivisionPerZero event
        return;
      }
     }

    double num = dividend/divisor;

    if (DivisionDone != null)
    {
      DivisionDone(this, new DivisionEventArgs(dividend, divisor, num)); //Execute the DivisionDone event
    }
  }
}

class DivisionEventArgs : EventArgs //The arguments of the division.
{
  public DivisionEventArgs(int a, int b, double r)
  {
    dividend = a;
    divisor = b;
    result = r;
  }

  private int dividend;
  private int divisor;
  private double result;

  public int Dividend
  {
    get { return dividend; }
  }

  public int Divisor
  {
    get { return divisor; }
  }

  public double Result
  {
    get { return result; }
  }
}


And you can use it like that :

private void TESTING_METHOD()
{
    Division division = new Division();
    division.DivisionDone += new Division.EventHandler(div_DivisionDone);
    division.DivisionPerZero += new Division.EventHandler(div_DivisionPerZero);

    division.Divide(10, 5);
}


Recommended Free Ebook
Similar Articles