From Schmid.wiki
Jump to: navigation, search

Example

using System;

public class Monster
{
    // delegate type declaration
    public delegate void EatHandler(string food);

    // event declarations
    public event EatHandler StartedEating;
    public event EatHandler DoneEating;

    public void DoStuff()
    {
        StartedEating("a man"); // raise StartedEating event
                                // - invoke underlying delegate
                                //   if invocation list is non-empty

        DoneEating("a man");    // raise DoneEating event
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        Monster godzilla = new Monster();

        // bind Monster_StartedEating to godzilla.StartedEating event
        godzilla.StartedEating +=
            new Monster.EatHandler(Monster_StartedEating);

        // bind Monster_DoneEating to godzilla.DoneEating event
        godzilla.DoneEating += new Monster.EatHandler(Monster_DoneEating);

        godzilla.DoStuff();
    }

    // Test's event handler for Monster.StartedEating event
    static void Monster_StartedEating(string food)
    {
        Console.WriteLine("monster started eating " + food);
    }

    // Test's event handler for Monster.DoneEating event
    static void Monster_DoneEating(string food)
    {
        Console.WriteLine("monster stopped eating " + food);
    }
}

Output:

monster started eating a man
monster stopped eating a man