Delegates & Events
Delegates and Events are important features of C# used to implement flexible, reusable, and event-driven programming. Delegates provide a way to reference methods, while events are used to notify other parts of an application when something happens.
What is a Delegate?
A delegate is a type that can hold a reference to a method. The method assigned to a delegate must have a compatible signature with the delegate.
Delegates are commonly used for callbacks, event handling, notifications, and passing methods as parameters.
Delegate Syntax
delegate returnType DelegateName(parameters);
Simple Delegate Example
delegate void MessageDelegate();
class Program
{
static void ShowMessage()
{
Console.WriteLine("Welcome to CIIT Training Institute 👨🏫❤️...!");
}
static void Main()
{
MessageDelegate message = ShowMessage;
message();
}
}
Output
Welcome to CIIT Training Institute 👨🏫❤️...!
Delegate with Parameters
A delegate can also reference a method that accepts parameters.
delegate void CalculateDelegate(int a, int b);
class Program
{
static void Add(int a, int b)
{
Console.WriteLine(a + b);
}
static void Main()
{
CalculateDelegate calculate = Add;
calculate(10, 20);
}
}
Output
30
Delegate with Return Value
A delegate can reference a method that returns a value.
delegate int CalculateDelegate(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
CalculateDelegate calculate = Add;
int result = calculate(10, 20);
Console.WriteLine(result);
}
}
Output
30
Multicast Delegate
A multicast delegate can reference more than one method. The methods are executed in the order in which they are added.
delegate void MessageDelegate();
class Program
{
static void FirstMessage()
{
Console.WriteLine("First Message");
}
static void SecondMessage()
{
Console.WriteLine("Second Message");
}
static void Main()
{
MessageDelegate message = FirstMessage;
message += SecondMessage;
message();
}
}
Output
First Message
Second Message
Action Delegate
Action is a built-in generic delegate that can reference a method returning void.
Action message = () =>
{
Console.WriteLine("Hello from Action");
};
message();
Output
Hello from Action
Func Delegate
Func is a built-in generic delegate used when a method returns a value.
Func<int, int, int> add =
(a, b) => a + b;
int result = add(10, 20);
Console.WriteLine(result);
Output
30
Events in C#
An event is used to notify other parts of an application when a particular action occurs.
Creating an Event
Events are commonly declared using a delegate type. Other objects can subscribe to the event and receive notifications.
class Order
{
public event Action OrderPlaced;
public void PlaceOrder()
{
Console.WriteLine("Order placed.");
OrderPlaced?.Invoke();
}
}
class Program
{
static void Main()
{
Order order = new Order();
order.OrderPlaced += SendNotification;
order.PlaceOrder();
}
static void SendNotification()
{
Console.WriteLine("Notification sent.");
}
}
Output
Order placed.
Notification sent.
Event Subscription
The += operator is used to subscribe a method to an event.
order.OrderPlaced += SendNotification;
The method will be called when the event is raised.
Removing an Event Handler
The -= operator is used to unsubscribe a method from an event.
order.OrderPlaced -= SendNotification;
Event with Custom Event Arguments
Events can pass additional information using EventArgs-derived classes.
class OrderEventArgs : EventArgs
{
public int OrderId { get; set; }
}
class Order
{
public event EventHandler<OrderEventArgs> OrderPlaced;
public void PlaceOrder(int orderId)
{
Console.WriteLine("Order placed.");
OrderPlaced?.Invoke(
this,
new OrderEventArgs
{
OrderId = orderId
});
}
}
class Program
{
static void Main()
{
Order order = new Order();
order.OrderPlaced += HandleOrderPlaced;
order.PlaceOrder(101);
}
static void HandleOrderPlaced(
object sender,
OrderEventArgs e)
{
Console.WriteLine(
"Order ID: " + e.OrderId);
}
}
Output
Order placed.
Order ID: 101
Delegate vs Event
| Feature | Delegate | Event |
|---|---|---|
| Purpose | References methods | Provides notifications |
| Invocation | Can be invoked by its holder | Normally raised by its declaring type |
| Common Usage | Callbacks | Event-driven programming |
| Example | Action, Func | Button click, order placed |
Example ❤️👨🏫
Consider an e-commerce application. When a customer places an order, multiple actions may need to happen, such as sending a notification, updating inventory, and creating an invoice.
class OrderService
{
public event Action OrderPlaced;
public void PlaceOrder()
{
Console.WriteLine("Order created.");
OrderPlaced?.Invoke();
}
}
class Program
{
static void Main()
{
OrderService service = new OrderService();
service.OrderPlaced += SendEmail;
service.OrderPlaced += UpdateInventory;
service.PlaceOrder();
}
static void SendEmail()
{
Console.WriteLine("Email notification sent.");
}
static void UpdateInventory()
{
Console.WriteLine("Inventory updated.");
}
}
Output
Order created.
Email notification sent.
Inventory updated.
Common Mistakes
- Using a delegate with an incompatible method signature.
- Forgetting to subscribe to an event.
- Forgetting to unsubscribe event handlers when required.
- Raising an event without checking whether it has subscribers.
- Using delegates when a simpler method call would be enough.
- Confusing the purpose of delegates and events.
Interview Questions
1. What is a delegate in C#?
A delegate is a type-safe reference to a method.
2. What is a multicast delegate?
A multicast delegate can reference multiple methods and invoke them together.
3. What is an event?
An event is a mechanism used to notify subscribers when something happens in an application.
4. What is the difference between delegate and event?
A delegate is primarily used to reference and invoke methods, while an event provides controlled notification to subscribers.
5. What are Action and Func?
Action represents a delegate that returns void, while Func represents a delegate that returns a value.
6. What is the use of += with events?
The += operator subscribes a method to an event.
Summary
Delegates provide a type-safe way to reference methods and are commonly used for callbacks and flexible method execution.
You also learned about multicast delegates, built-in Action and Func delegates, and how multiple methods can be associated with a delegate.
Events provide a controlled way to notify subscribers when an action occurs. They are widely used in event-driven applications and notification systems.
Understanding Delegates and Events is important for developing flexible and maintainable .NET and ASP.NET Core applications.
Practice Questions
- Create a delegate that references a simple method.
- Create a delegate with two integer parameters.
- Create a delegate that returns an integer value.
- Create a multicast delegate with two methods.
- Demonstrate the Action delegate.
- Demonstrate the Func delegate.
- Create an event for an order placement operation.
- Subscribe a method to an event.
- Unsubscribe a method from an event.
- Create an event using EventHandler and custom EventArgs.
- Explain the difference between delegates and events.
- Explain real-world applications of delegates and events.