C# Events

In c#, event is a message which is sent by an object to indicate that particular action is going to be happen. The action could be caused either by button click, mouse movements or by some other programming logic. The object that raises an event is called event sender.

 

In simple words, we can say that events are used to signal an user actions such as button click, mouse over, menu selection, etc. in user interface of windows and web applications.

 

Generally, an event is nothing but a something special that is going to happen. For example, Microsoft or Google will conduct a Build / Keynote events to announce their new features or products and they will notify about their events to the users either through an email or advertisements. Here Google or Microsoft is a publisher who conducts (or raises) an event and users become a subscribers to attend (or handle) the event.

 

In c#, events will follow the same pattern and it will contain a publisher, subscriber, notification and handler. The events will enable a class or object to notify other classes or objects when something of special happens. The class that sends (or raises) an event is called publisher and the class that receives (or handle) an event is called subscriber.

 

In c#, the publisher will determines when an event is raised and the subscribers will determine what action can be taken in response to the event. An event in c# will have a multiple subscribers and the events that have no subscribers will never be raised. The subscriber can handle a multiple events from multiple publishers.

 

Now we will see how to create and use an events in c# to notify other classes or objects when something of interest happens.

C# Events Declaration

In c#, events are the encapsulated delegates so first we need to define a delegate before we declare an event inside of a class by using event keyword.

 

Following is the example of declaring an event using event keyword in c# programming language.

 

// Declare the delegate

public delegate void SampleDelegate();

//Declare an event

public event SampleDelegate SampleEvent;

If you observe above event declaration, first we declared a delegate (SampleDelegate) and we made that delegate as an event (SampleEvent) by using event keyword.

 

In c#, to raise an event we need to invoke the event delegate and subscribe to an event using += operator. In case, if you want to unsubscribe from an event, then use -= operator.

 

To respond to an event, we need to define an event handler method in the event receiver and this method signature must match with the signature of event delegate. In event handler, we can perform an actions that are required whenever the event is raised, such as getting the user input after click on button.

C# Events Example

Following is the example of declaring and raising an event using underlying delegate type in c# programming language.

 

using System;

 

namespace Tutlane

{

    class Maths

    {

        // Declare the delegate

        public delegate void SampleDelegate();

        //Declare an event

        public event SampleDelegate SampleEvent;

        public void Add(int a, int b)

        {

            // Calling event delegate to check subscription

            if (SampleEvent != null)

            {

                // Raise the event by using () operator

                SampleEvent();

                Console.WriteLine("Add Result: {0}", a + b);

            }

            else

            {

                Console.WriteLine("Not Subscribed to Event");

            }

        }

        public void Subtract(int x, int y)

        {

            // Calling event delegate to check subscription

            if (SampleEvent != null)

            {

                // Raise the event by using () operator

                SampleEvent();

                Console.WriteLine("Subtract Result: {0}", x - y);

            }

            else

            {

                Console.WriteLine("Not Subscribed to Event");

            }

        }

    }

    class Operations

    {

        Maths m;

        public int a { get; set; }

        public int b { get; set; }

        public Operations(int x, int y)

        {

            m = new Maths();

            // Subscribe to SampleEvent event

            m.SampleEvent += SampleEventHandler;

            a = x;

            b = y;

        }

        // SampleEvent Handler

        public void SampleEventHandler()

        {

            Console.WriteLine("SampleEvent Handler: Calling Method");

        }

        public void AddOperation()

        {

            m.Add(a, b);

        }

        public void SubOperation()

        {

            m.Subtract(a, b);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("****Events Example****");

            Operations op = new Operations(10, 20);

            op.AddOperation();

            op.SubOperation();

            Console.ReadLine();

        }

    }

}

If you observe above example, we created a Maths class (publisher) and Operations class (subscriber) with required methods and SampleEvent event. In Maths class methods, we are checking the condition like whether the calling class subscribed to SampleEvent event or not to execute the required functionality.

 

In Operations class, we subscribed to SampleEvent event using += operator and mentioned the name of handler (SampleEventHandler) to perform the required operations when an event is raised.

 

If you observe the handler method (SampleEventHandler) in Operations class, it’s having the same signature of our delegate (SampleDelegate) in Maths class.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Events Example Result

C# Events Overview

Following are the improtant points which we need to remember about events in c# programming language.

 

  • In c#, events are used to enable a class or object to notify other classes or objects about the action that is going to happen. 
  • To declare an event, we need to use event keyword with delegate type.
  • Before raising an event, we need to check whether an event is subscribed or not.
  • By using += operator, we can subscribe to an event and by using -= operator we can unsubscribe from an event.
  • To raise an event, we need to invoke the event delegate.
  • To respond to an event, we can define an event handler method in the event receiver and the handler method must have the same signature of delegate in the event.
  • In c#, to raise an events there must be a subscribers otherwise they won’t be raised.
  • In c#, an event can have multiple subscribers and a subscriber can handle multiple events from multiple publishers.
  • In case, an event have multiple subscribers, then an event handlers are invoked synchronously when an event raised.
  • In c#, the publisher determines when an event is raised, the subscriber determine what action is taken in response to the event.
  • In .NET Framework, events are based on EventHandler delegate and an EventArgs base class. 
 

PREVIOUS

C# Delegates