Sponsored Ad

Monday, September 28, 2009

C# Event

An event is a mechanism via which a class can notify its clients when something happens. For example when you click a button, a button-click-event notification is sent to the window hosting the button. Events are declared using delegates. So if you don't know what a delegate is,  Just try out the sample program and go through the sample source, line by line. Maybe, you can read the article once more after that. Once you get the hang of it, things will seem simple.

using System;
public delegate void DivBySevenHandler(object o, DivBySevenEventArgs e);
public class DivBySevenEventArgs : EventArgs
{
    public readonly int TheNumber;
    public DivBySevenEventArgs(int num)
    {
        TheNumber = num;
    }   
}
public class DivBySevenListener
{
    public void ShowOnScreen(object o, DivBySevenEventArgs e)
    {
        Console.WriteLine(
            "divisible by seven event raised!!! the guilty party is {0}",
            e.TheNumber);
    }   
}
public class BusterBoy
{
    public static event DivBySevenHandler EventSeven;
    public static void Main()
    {
        DivBySevenListener dbsl = new DivBySevenListener();
        EventSeven += new DivBySevenHandler(dbsl.ShowOnScreen);
        GenNumbers();
    }
    public static void OnEventSeven(DivBySevenEventArgs e)
    {
        if(EventSeven!=null)
            EventSeven(new object(),e);
    }   
    public static void GenNumbers()
    {
        for(int i=0;i<99;i++)
        {
            if(i%7==0)
            {
                DivBySevenEventArgs e1 = new DivBySevenEventArgs(i);
                OnEventSeven(e1);
            }
        }       
    }
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers