C# Events: The Events enable a class or object to notify other classes or objects when some interesting thing happens to the object. A class that sends or raises the event is called the publisher, and the classes that receive or handle the event are referred to as subscribers.
There can be multiple subscribers to a single event. Typically, when an action takes place, a publisher raises an event. The subscribers who want to be notified when an action takes place should register or subscribe to handle specific events.
The following diagram shows the event in C#.
Table of Contents
Events in C#
Events in C# are used to notify user actions such as button click, mouse over, menu selection, On Text Changed, etc.
An event is an encapsulated delegate in C#. It depends on the delegate. The delegate specifies the event handler method’s signature for the subscriber class.
- A publisher is an object that holds the definition of the event and the delegate. A publisher class object raises an event and is notified to other objects.
- A subscriber is an object that receives the event and provides an event handler. The delegate of the publisher class invokes the event handler of the subscriber class.
Event Syntax:
In C#, Events are declared using the event keyword followed by the name of the delegate.
The following is the event syntax:
event delegate_name event_name;
C# Events Declaration
An event can be declared in the following two steps:
- first, we need to declare a delegate.
- Then, declare a variable of delegate with the event keyword.
The following example shows how to declare an event in c# programming language.
public delegate void Notify(); // delegate
public event Notify myEvent; // event
Program to implement Events in C#
The C# program to implement events is shown below.
using System;
namespace CSharp_Events_Example
{
public delegate void Notify(string name); // Delegate
public class Program
{
event Notify myEvent; // Event
public Program() // Constructor
{
// Register with an event
this.myEvent += new Notify(this.Display);
}
public void Display(string name)
{
Console.WriteLine($"Hi: {name}");
}
static void Main(string[] args)
{
Program e = new Program();
e.myEvent("Shekh");
Console.ReadLine();
}
}
// Output: Hi: Shekh
}
Events Overview
These are the characteristics of events:
- An event is a wrapper around a delegate or, in simpler terms, it’s an encapsulated delegate.
- Events are used to implement a communication mechanism between objects.
- Events have publishers and subscribers. Publishers determine when events occur, and subscribers determine what actions to take in response to events.
- We can subscribe to an event using the
+=
operator and unsubscribe from an event using the-=
subtraction assignment operator. - A single event may have multiple subscribers. A subscriber is capable of handling multiple events from multiple publishers.
C# event handler with example
To respond to an event, an event receiver must define an event handler method. The signature of this method must match the signature of the delegate for the event it handles.
The event handler method contains the code that gets executed in response to a specific event that occurs in an application such as button clicks, mouse hover, menu selections, etc.
Now that we are clear on what an event handler is, let us write a simple syntax for an Event handler method as follows:
public delegate void sampleEventHandler(int num1, int num2);
The delegate declaration above has a basic operation that points to an event-handling method that accepts two parameters of integer type.
Example: EventHandler
The following example shows the event handler methods named Add & Substract that match the signature of the EventHandler delegate. These methods subscribe to the event named “MyEvent”.
using System;
namespace CSharp_Event_Handler_Example
{
// Declare delegate
public delegate void sampleEventHandler(int num1, int num2);
class Program
{
// Declare event
public static event sampleEventHandler MyEvent;
static void Main()
{
// Register event handler methods with an event
MyEvent += new sampleEventHandler(Add);
MyEvent += new sampleEventHandler(Substract);
MyEvent.Invoke(20,10);
Console.ReadLine();
}
// Event Handler methods
static void Add(int num1, int num2)
{
Console.WriteLine( $" Addition: {num1} + {num2} = {num1 + num2} ");
}
static void Substract(int num1, int num2)
{
Console.WriteLine($" Substraction: {num1} - {num2} = {num1 - num2} ");
}
}
}
The following image displays the results of the C# event handler program mentioned above.
Difference between events and delegates in C#
Sr.No. | C# Delegates | C# Events |
---|---|---|
1. | Delegates are declared using the delegate keyword. | Events are declared with the event keyword. |
2. | Delegate defines a function pointer. It holds the reference to one or more functions at runtime. | An event is a notification mechanism between objects that depends on delegates |
3. | A delegate can be declared both inside or outside of a class. | An event can only be declared inside a class. |
4. | In C#, delegates are independent of events. | An event can’t be created without delegates. |
5. | We can pass delegate as a method parameter. | However, an event is raised but can’t be passed as a method parameter. |
FAQs
Q: What does the term “event handler” mean in C#?
In C#, an event handler is a method that contains the code that gets executed in response to a particular event (user actions) that takes place in an application, such as a key press, a button click, a mouse movement, etc.
Q: Is there a difference between delegates and events in C#?
A delegate is a function pointer that holds the reference to one or more methods with the same signature at runtime. Delegates are independent and do not depend on events, but events depend on delegates and cannot be created without them.
Q: Why do we use delegates in C# programming?
Delegates let you pass methods as parameters. Delegates are mainly used in implementing call-back methods and events. Delegates can be chained together, so two or more methods can be called on a single event.
Q: What are C# events?
An event is a message sent by one object to notify another object that an action has occurred. This action can be caused by a (UI) user interaction such as a button click, mouse click, or key press.
Q: Can we create Events without a Delegate?
No, Events internally use Delegates. As a result, an event is dependent on a delegate and cannot be created without a delegate.
References: MSDN-Events (C# Programming Guide)
Articles to Check Out:
- C# Abstract class Vs Interface
- Sealed Class in C# with examples
- Generic Delegates in C# With Examples
- Serialization and Deserialization in C# with Example
- C# Array vs List: When should you use an array or a List?
- C# Monitor class in multithreading
- C# Struct vs Class
- C# Dictionary with Examples
I hope you liked reading this article “C# Events”. If you have any suggestions or would like to provide more details about the subject covered here, please leave a comment below.
- Difference Between Array And ArrayList In C#: Choosing the Right Collection - May 28, 2024
- C# Program to Capitalize the First Character of Each Word in a String - February 21, 2024
- C# Program to Find the Longest Word in a String - February 19, 2024