C# Events

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

 

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

 

Generally, an event is nothing but something special that is going to happen. For example, Microsoft or Google will conduct 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 subscriber 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 special happens. The class that sends (or raises) an event is called the publisher and the class that receives (or handle) an event is called subscriber.

 

In c#, the publisher will determine 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 multiple subscribers and the events that have no subscribers will never be raised. The subscriber can handle multiple events from multiple publishers.

 

Now we will see how to create and use 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 the event handler, you can perform actions that are required whenever the event is raised, such as getting the user input after a click on the 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 the 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 the 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 the Operations class, it’s having the same signature of our delegate (SampleDelegate) in Maths class.

 

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

 

C# Events Example Result

C# Events Overview

The following are the important 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 events there must be 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 has multiple subscribers, then event handlers are invoked synchronously when an event raised.
  • In c#, the publisher determines when an event is raised, the subscriber determines what action is taken in response to the event.
  • In .NET Framework, events are based on EventHandler delegate and an EventArgs base class. 

Topics Covered