Events in C#

During program execution, user interact with the program by clicking different screen areas, pressing different keys and hovering mouse at different places. All of these user actions are basically events. Events are also raised by system itself in the form of notifications and interrupts. This article explains how these events are handled and how certain piece of code can be executed as a result of these events.

Events in C# follow a publisher-subscriber model. Publisher is basically a class that contains the event declaration and corresponding delegate which contains referent to the event handler. Subscriber is the class which contains event handler which is nothing but a method which is executed when a certain event occurs. Sometimes, a publisher and subscriber can be same class. Have a look at the following code snippet to understand this concept.

´╗┐using System;
namespace CSharpTutorials{

    public delegate void delegateevent();
    public class EventPublisher {

        public static event delegateevent eventtofire;
        EventSubscriber es = new EventSubscriber();
        public void BindEvent()  {
            // Bind the event to evenhandlers
            eventtofire += new delegateevent(es.DisplayMessage);
            eventtofire += new delegateevent(es.DisplayMessage2);
        }
        public void InvokeEvent()  {
            //invoke the event
            eventtofire.Invoke();
        }
    }

    public class EventSubscriber {

        public void DisplayMessage()  {
            Console.WriteLine("An event has been fired");
        }
        public void DisplayMessage2() {
            Console.WriteLine("Another event has been fired");
        }
    }

    class Tutorial {

        static void Main() {
            EventPublisher pub = new EventPublisher();

            pub.BindEvent();
            pub.InvokeEvent();
            Console.ReadKey();
        }
    }
}

Download the code

In the above code EventPublisher and EventSubscriber classes have been created. EventPublisher class contains delegate which should match the syntax of the event handler that will be triggered once an event is called. The event itself should also be of the delegate type. In the EventSubscriber class, we have two methods DisplayMessage1, and DisplayMessage2. We want that when our event is triggered, these two event handlers should be called.

To do so, we need to bind the event with the handler, this is done by using “+=” operator where event is on the left side and the event handlers are passed to the delegate type object. This way, you can bind multiple event handlers with one event. Finally, to invoke the event, the Invoke function is called on the object which triggers the event.s

<<< Delegates in C#Properties in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .