C# - Events



Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.

Using Delegates with Events

The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriber class. Events use the publisher-subscriber model.

A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.

A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.

Declaring Events

To declare an event inside a class, first of all, you must declare a delegate type for the even as:

public delegate string BoilerLogHandler(string str);

then, declare the event using the event keyword −

event BoilerLogHandler BoilerEventLog;

Example of C# Event

The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised.

using System;
namespace SampleApp {
   public delegate string MyDel(string str);
	
   class EventProgram {
      event MyDel MyEvent;
		
      public EventProgram() {
         this.MyEvent += new MyDel(this.WelcomeUser);
      }
      public string WelcomeUser(string username) {
         return "Welcome " + username;
      }
      static void Main(string[] args) {
         EventProgram obj1 = new EventProgram();
         string result = obj1.MyEvent("Tutorials Point");
         Console.WriteLine(result);
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Welcome Tutorials Point

Event Handling Example Using Delegates

Following is the another example demonstrating C# event handling using delegates, where we trigger an event when a user logs in:

using System;
namespace EventExample {
   public delegate void Notify(string message);
   
   // Publisher class
   class User {
      // Declare event
      public event Notify UserLoggedIn;
      
      public void Login(string username) {
         Console.WriteLine($"{username} logged in successfully.");
         
         // Trigger event
         UserLoggedIn?.Invoke($"Notification: {username} has logged in.");
      }
   }
   
   // Subscriber class
   class Program {
      static void Main(string[] args) {
         User user = new User();
         
         // Subscribe to the event
         user.UserLoggedIn += DisplayMessage;
         
         // Simulate login
         user.Login("JohnDoe");
      }
      
      // Event handler method
      static void DisplayMessage(string message) {
         Console.WriteLine(message);
      }
   }
}

Following is the output of the above code −

JohnDoe logged in successfully.
Notification: JohnDoe has logged in.

Event with Multiple Handlers

You can use multiple handlers for a single event. This is implemented using the delegates. When an event is triggered, all subscribed methods are called in the order they were added.

Example

The following example demonstrates an event with multiple handlers. In this example, we create a class called WeatherStation. It has an event named OnTemperatureAlert that uses a delegate called TemperatureAlertHandler. When the temperature goes above a set limit, two handlers DisplayDevice and CoolingSystem are called.

using System;

class WeatherStation {
    public delegate void TemperatureAlertHandler(string message);
    public event TemperatureAlertHandler OnTemperatureAlert;

    public void CheckTemperature(double temperature) {
        Console.WriteLine($"Current temperature is: {temperature}");
        if (temperature > 30) {
            OnTemperatureAlert?.Invoke("Temperature too high...");
        }
    }
}

class Program {
    static void DisplayDevice(string msg) => Console.WriteLine($"Display shows alert: {msg}");
    static void CoolingSystem(string msg) => Console.WriteLine($"Cooling system activated: {msg}");

    static void Main() {
        WeatherStation station = new WeatherStation();

        station.OnTemperatureAlert += DisplayDevice;
        station.OnTemperatureAlert += CoolingSystem;

        station.CheckTemperature(35.5);
    }
}

When the above code is compiled and executed, it produces the following result −

Current temperature is: 35.5
Display shows alert: Temperature too high...
Cooling system activated: Temperature too high...
Advertisements