C sharp - Delegates & Events in C#
1. What is a Delegate?
A delegate in C# is a type that represents references to methods with a specific parameter list and return type.
Think of it as a type-safe function pointer.
It allows you to store a method inside a variable and call it later.
Why Delegates Are Needed
-
To pass methods as parameters
-
To implement callback mechanisms
-
To enable event-driven programming
-
To support functional-style programming
2. Basic Delegate Syntax
public delegate int Operation(int a, int b);
This means:
-
The delegate name is
Operation -
It can reference any method that:
-
Returns
int -
Accepts two
intparameters
-
Example usage:
class Program
{
public static int Add(int x, int y)
{
return x + y;
}
static void Main()
{
Operation op = Add;
int result = op(5, 3);
Console.WriteLine(result); // Output: 8
}
}
Here:
-
opholds reference to methodAdd -
Calling
op(5,3)callsAdd(5,3)
3. Multicast Delegates
Delegates in C# can hold multiple methods.
Operation op = Add;
op += Multiply;
When invoked:
-
Both methods execute
-
Only the result of the last method is returned
This is called a Multicast Delegate.
4. Built-in Delegates
Instead of creating custom delegates, C# provides built-in ones:
Action
-
No return value
Action<string> greet = name => Console.WriteLine("Hello " + name);
greet("Vidhi");
Func
-
Returns a value
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(2, 3));
Predicate
-
Returns boolean
Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4));
These reduce unnecessary delegate definitions.
5. What Are Events?
An event is a wrapper around a delegate.
It is used to implement the publisher-subscriber pattern.
-
Publisher → Raises the event
-
Subscriber → Handles the event
Events are widely used in:
-
GUI programming
-
Button click handling
-
Notifications
-
Real-time systems
6. Event Example
using System;
class Publisher
{
public delegate void Notify();
public event Notify OnProcessCompleted;
public void StartProcess()
{
Console.WriteLine("Process Started...");
OnProcessCompleted?.Invoke();
}
}
class Subscriber
{
public void Message()
{
Console.WriteLine("Process Completed!");
}
}
class Program
{
static void Main()
{
Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
pub.OnProcessCompleted += sub.Message;
pub.StartProcess();
}
}
Output:
Process Started...
Process Completed!
7. Why Use Events Instead of Delegates Directly?
If you use delegates directly:
public Notify OnProcessCompleted;
Anyone can:
-
Overwrite it
-
Invoke it
-
Remove other subscribers
But with event keyword:
-
Only the class can invoke it
-
Outside classes can only subscribe/unsubscribe
This provides encapsulation and safety.
8. Real-World Use Case
In Windows Forms or WPF:
button.Click += Button_Click;
Here:
-
Clickis an event -
Button_Clickis the event handler
This is pure delegate-based event handling.
9. Important Concepts
-
Delegates are reference types
-
Delegates are immutable
-
Events are based on delegates
-
Lambda expressions work with delegates
-
Used heavily in async and LINQ
Summary
| Concept | Purpose |
|---|---|
| Delegate | Store method reference |
| Multicast Delegate | Store multiple methods |
| Event | Safe delegate wrapper |
| Action / Func | Built-in delegate types |
| Usage | Callbacks, GUI, async, notifications |