c sharp

How to Implement and Use Event Handlers in C#

C# is an incredible programming language that comes with a ton of features for a wide array of applications. However, one of the most renowned features of C# is its support and emphasis on Object Oriented Programming.

One of the major features of OOP is object communication which is facilitated by events. Events refers to a way that allows a class to provide notification and means of communication to the clients of the class. This ensures that the clients of the class are updated when an interesting event happens.

Any class that raises an event is known as a publisher while the client that receive and act on the event are known as subscribers.

In this tutorial, we will walk you through the fundamentals of working with events in C#. This allows us to create pub/sub apps in C#.

The Basics

Let us explore some basic concepts and building blocks of events in C# before delving into the code.

C# Event

The first and most important part is the actual event. An event itself is a message that is sent by an object to signal the occurrence of a specific action.

C# Delegate

Next, we have what is known as a delegate. A delegate is a type that defines the method signature and provides a reference to any method with a compatible signature.

We can invoke the method using the instance of the delegate.

Lastly, we have the EventArgs which is used to define the base class for classes that contain the event data.

How to Build and Run the Events

In C#, we can follow the following steps to create and handle the events:

  1. The first step is creating a delegate which defines the method signature of the event.
  2. Next, we declare an event in the clas.
  3. Then, we raise an event by calling the delegate.
  4. Lastly, we define an event handler which specifies all the events to run the event.

Example Demonstration:

Consider the following example that demonstrates how we can implement the previous logic:

Define the Delegate

Let us start by defining the delegate. In this case, we use a simple delegate called “EventHandler” that takes the parameter of type “EventArgs” and returns a void.

The example code is as follows:

public delegate void EventHandler(object source, EventArgs args);

Declare an Event

The second part is declaring an event inside a class. In this case, we call it “SimpleEvent” and allow it to use the delegate of type “EventHandler” as defined in the previous step.

public class EventPublisher

{

  public event EventHandler SimpleEvent;

}

Raise the Event

Next, we can create a method to raise the event. We can raise an event using the “?.Invoke” method as follows:

public class EventPublisher
{
    public event EventHandler SimpleEvent;

    public void RaiseEvent()
    {
        Console.WriteLine("Event is being raised!");
        SimpleEvent?.Invoke(this, EventArgs.Empty);
    }
}

Handle the Event

As you can guess, the next step is defining a class to handle the event. We can define the class as follows:

public class EventSubscriber
{
    public void NewEvent(object source, EventArgs args)
    {
        Console.WriteLine("Event received by EventSubscriber object!");
    }
}

Use the Event

Once we defined the publisher and subscriber, we can subscribe to the event and raise it as follows:

public class Program
{
    public static void Main()
    {
        EventPublisher publisher = new EventPublisher();
        EventSubscriber subscriber = new EventSubscriber();

        publisher.SimpleEvent += subscriber.NewEvent;

        publisher.RaiseEvent();
    }
}

Running the previous code should return the following:

Event is being raised!
Event received by EventSubscriber object!

Conclusion

This basic tutorial provided a code-guided tutorial on how to create and work with event handlers in C#.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list