C# Events

An event is a mechanism for communication between objects. When something happens such as a key press or an error, an event can notify other objects about it.

C# Events are used for inter-process communication. Events are known as the user actions such as mouse movements, keypress, and clicks, etc. In C# applications have to respond to events when they occur.

To declare events in C#, we declare them in class and associate with the event handlers using delegates within the same class or any other class.

The class containing the event is used to publish the event at that particular time is known as Publisher Class. The other class which accepts this event is known as the Subscriber class. Events are based on the publisher-subscriber model.

The difference between Publisher and Subscriber is given below:
  • publisher is defined as an object that contains the definition of the event and the delegate. The event-delegate association is declared in this object. A publisher class object invokes the event and it is notified to other objects.
  • subscriber is known as 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.

Events are used in two stages. An event is published by the class that contains the event, and classes that accept the event, subscribe to it.

  • The publisher is the object that contains the definition of the event and the delegate. When the publisher class invokes the event, it notifies the subscribers.
  • The subscriber is the object that accepts and handles the event. The delegate from the publisher class invokes the handling method of the subscriber class

Declaring Events in C#

Before we can declare the event, we must declare a delegate type for the event. To declare an event, we use the event keyword before the delegate type. Following is the example explaining the C# events.

using System;

namespace events {
   public delegate string Myevent(string str);
	
  public class EventProgram {
      event Myevent MyEvent;
		
      public EventProgram() {
         this.MyEvent += new Myevent(this.WelcomeUser);
      }
      public string WelcomeUser(string username) {
         return "CSahrp " + username;
      }
      public static void Main(string[] args) {
         EventProgram obj1 = new EventProgram();
         string result = obj1.MyEvent("Events");
         Console.WriteLine(result);
      }
   }
}