1Why Do We Need Delegates and Events?
Hi friends! In this article, we will learn Delegates, Events and Lambda Expressions in C#. These three concepts help us write flexible and reusable code. A delegate allows us to pass a method as a parameter. An event allows one object to notify other objects when something happens. A lambda expression provides a shorter way to write a method. We commonly use them in event handling, callbacks, LINQ and asynchronous programming.
2Think About an Online Payment
Imagine you are making a payment using a UPI application. Once the payment is successful, the application needs to send a notification, update the transaction history and generate a receipt.
The payment service does not need to know how every notification works. It simply announces that payment is completed. Other components can subscribe and respond.
This is where delegates and events become useful. Lambda expressions can also help us write those notification methods quickly.
3Understand These Three Concepts
1. Delegate
A delegate is a type-safe reference to a method. It defines which method signature can be assigned and invoked.
2. Event
An event is a notification mechanism built on delegates. Subscribers can register methods and receive notifications when the event is raised.
3. Lambda Expression
A lambda expression is a short way to write an anonymous function using the => operator.
| Concept | Purpose |
|---|---|
| Delegate | Reference and invoke methods. |
| Event | Notify subscribed methods. |
| Lambda | Write short functions. |
4Let's Write the C# Program
Let's build a small payment notification application. We will use a custom delegate, a lambda expression and an event.
using System;
public delegate void Notification(string message);
class PaymentService
{
public event Action<string>? PaymentCompleted;
public void Pay()
{
Console.WriteLine("Payment successful!");
PaymentCompleted?.Invoke("UPI123");
}
}
class Program
{
static void Main()
{
Notification notify = message =>
Console.WriteLine("Delegate: " + message);
notify("Welcome!");
Notification upper = message =>
Console.WriteLine("Lambda: " + message.ToUpper());
upper("payment successful");
PaymentService service = new();
service.PaymentCompleted += id =>
Console.WriteLine("Email sent for " + id);
service.PaymentCompleted += id =>
Console.WriteLine("SMS sent for " + id);
service.Pay();
}
}
First, we create a custom delegate called Notification. We assign lambda expressions to delegate variables and invoke them. Next, PaymentService exposes an event. Two subscribers register using +=. When Pay() executes, both subscribers receive the payment notification.
5Check the Console Result
Run the console application. You will see the following output in the same order as the method calls and event subscriptions.
Delegate: Welcome! Lambda: PAYMENT SUCCESSFUL Payment successful! Email sent for UPI123 SMS sent for UPI123
Notice that both email and SMS subscribers execute when the payment event is raised.
6Watch Delegates and Events Run in VS Code
Follow the code as it is typed, executed and displayed in the terminal. Watch how the event notifies both subscribers.
⌕
⑂
▣
7Let's Revise What We Learned
Delegates allow us to pass methods as parameters. Events help objects communicate through notifications. Lambda expressions make functions shorter and easier to write.
- Delegate: Holds a reference to a compatible method.
- Event: Notifies registered subscribers.
- Lambda: Writes an anonymous function using =>.
8Questions Interviewers Love to Ask
What is a delegate in C#?
Answer
A delegate is a type-safe reference to a method. It allows methods to be passed as parameters and invoked through the delegate.
What is the difference between a delegate and an event?
Answer
A delegate references methods and can invoke them. An event provides controlled subscription and notification using a delegate.
What is the difference between Action and Func?
Answer
Action represents a delegate that does not return a value. Func represents a delegate that returns a value.
What is a lambda expression?
Answer
A lambda expression is an anonymous function written using the => operator. It is commonly used with delegates, LINQ and event subscriptions.
Can multiple methods subscribe to an event?
Answer
Yes. Multiple methods can subscribe using +=. When the event is raised, all registered handlers are invoked in subscription order.