Home > Tutorial for Beginners > C# events and event handlers

C# events and event handlers

What are Events in C#: In simple terms event means happening or action or occurrence of anything. Event can be anything it can be mouse click, enter key press, lost focus. In other words they are the notification, means something is going to change or ready to happen. Handling of the event is known as response. for example when you click on a button another page opens, here button click is an event and second part is the response of that events.  When events happens a notification sent to client so that client can prepare the response.


I am going to explain event handling in a very simple way, let’s suppose you have many objects in your application and they interact with other, now you tell me how you will know which of these many objects has changed their state? Any guess? Yes C sharp has the answer. You can do it by using

  • Event source
  • Event Handler

Event Source: It is responsible to inform other objects that something has changed.
Event Handler: When event source publish their signals about the changes, event handler receive those signals or events.  It can be static or non static method of your class. You can register multiple event handlers for one event.

In c share they are somehow related with delegates. Delegates plays a very important role in c sharp, they carries information from event source to event handler and taking back to the event source. It works between event source and event handlers. Events and Event handling are declared in a same class or another class with the help of delegates.

How to declare Events:
First you have to declare one delegates then events as

  public delegate void TimeToSleep();
//Associate event
  private event TimeToSleep PowerOff;

How to Handle/Subscribe:

Let’s assume my PG class has one method “plssleep” which fires when the power goes off as

myPG obj = new myPG();
PowerOff = new TimeToSleep(obj.plsSleep);

public class myPG
   public void plsSleep()
       //your code

Post Comments Below

  1. No comments yet.
  1. No trackbacks yet.