Maha

Maha

  • NA
  • 600
  • 71.4k

Events and Delegate

Nov 22 2015 8:38 AM

Both programs are using event but one program is using delegate with event. Please tell when to use event only and when to use event and delegate.

 Delegate and Event

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();

         Console.ReadKey();

    }

     static void Cat()

    {

        Console.WriteLine("Cat");

    }

     static void Dog()

    {

        Console.WriteLine("Dog");

    }

     static void Mouse()

    {

        Console.WriteLine("Mouse");

    }

}

/*

Dog

Cat

Mouse

Mouse

*/

 Event only

 using System;

 class MyEvent

{

    public event EventHandler SomeEvent; // uses EventHandler delegate

     // This is called to fire SomeEvent.

    public void OnSomeEvent()

    {

        if (SomeEvent != null)

            SomeEvent(this, EventArgs.Empty);

    }

}

public class EventDemo6

{

    static void handler(object source, EventArgs arg)

    {

        Console.WriteLine("Event occurred");

        Console.WriteLine("Source is " + source);

    }

     public static void Main()

    {

        MyEvent evt = new MyEvent();

         // Add handler() to the event list.

        evt.SomeEvent += new EventHandler(handler);

         // Fire the event.

        evt.OnSomeEvent();

         Console.ReadKey();

    }

}

/*

Event occurred

Source is MyEvent

*/


Answers (6)