Aug 8, 2015

Event Handler in Csharp

An event can have many handlers. With the event handler syntax, we create a notification system. We attach additional methods without changing other parts of the code. This makes programs easier to maintain.

Example. First, this example shows the event keyword. It creates an original event.


Based on: .NET 4.5

C# program that uses event handler

using System;

public delegate void EventHandler();

class Program
{
    public static event EventHandler _show;

    static void Main()
    {
 // Add event handlers to Show event.
 _show += new EventHandler(Dog);
 _show += new EventHandler(Cat);
 _show += new EventHandler(Mouse);
 _show += new EventHandler(Mouse);

 // Invoke the event.
 _show.Invoke();
    }

    static void Cat()
    {
 Console.WriteLine("Cat");
    }

    static void Dog()
    {
 Console.WriteLine("Dog");
    }

    static void Mouse()
    {
 Console.WriteLine("Mouse");
    }
}

Output

Dog
Cat
Mouse
Mouse

No comments:

Post a Comment