Tutorial details
Name : Events and Delegates
Author : Kenneth Clark
Language : C#
Platform : Windows 2000/XP
Click here if you require development or hosting solutions : [ SkyeTech Solutions ]

Events and delegates allow us to trap the event and execute an action against it.

They are actually quiet easy to use. First we set up a basic class

public class MyTestClass{
  private int total;
  
  public int Total{
    get{return this.total;}
  }
}
Then we add some functions to it
public void AddTwo(int i, int j){
  this.total = i + j;
}
Right now that we have a basic class and a basic function it is time to add the extras.
public delegate void MathOps();
public static event MathOps Complete;
Okay now our class looks like this
public class MyTestClass{
  private int total;
  
  public delegate void MathOps();
  public static event MathOps Complete;

  public void AddTwo(int i, int j){
    this.total = i + j;
    Complete(); //note this line
  }

  public int Total{
    get{return this.total;}
  }
}
So what? I hear you asking, well this is where the real fun comes in. To use the events we code another class to test it in.
public class MyOutputClass{

  private MyTestClass test	= null;

  public void WriteTotal(){
    Console.WriteLine(test.Total.ToString());
  }

  public MyOutputClass(){
    this.test		= new MyTestClass();
    MyTestClass.Complete += 
                        new MyTestClass.MathOps(WriteTotal);
    this.test.AddTwo(5,7);
  }
}	
So what is happening is that when the MyTestClass.AddTwo function is called it adds the two numbers together. Then the function assigned to MyTestClass.MathOps is execute once AddTwo fires the Complete event.

Nice and simple really. Below is the entire thing as a console application. These events are very usefully for many things and I use them mainly to trap events between windows.

using System;
using System.Collections.Generic;
using System.Text;

namespace EventDelegates {
  public class MyTestClass{
    private int total;
    public delegate void MathOps();
    public static event MathOps Complete;

    public void AddTwo(int i, int j){
      this.total = i + j;
      Complete();
    }

    public int Total{
      get{return this.total;}
    }
  }

  public class MyOutputClass{

    private MyTestClass test	= null;

    public void WriteTotal(){
      Console.WriteLine(test.Total.ToString());
    }

    public MyOutputClass(){
      this.test		= new MyTestClass();
      MyTestClass.Complete += 
                       new MyTestClass.MathOps(WriteTotal);
      this.test.AddTwo(5,7);
    }
  }

  class Program {
    static void Main(string[] args) {
      MyOutputClass output	= new MyOutputClass();
    }
  }
}

Once again, if you get stuck, give us a shout



SkyeTX Technologies Business Software Solutions
SkyeTX Technologies Business Software Solutions