Delegates in C# are powerful tools that allow methods to be passed as parameters. They are the foundation of events and callback methods in .NET, providing flexibility and extensibility in your applications.
Here's a clear and informative article on C# Delegates, including examples and explanations suitable for beginners or intermediate-level developers.
Getting Started
In C sharp, delegates are type-safe function pointers. They allow you to reference methods with a specific signature and invoke them at runtime. Delegates are particularly useful for implementing events, callbacks, and LINQ expressions.
What Does Delegate Meaning
A delegate is a type that represents references to methods with a particular parameter list and return type. In simple terms, it’s like a pointer to a function in C or C++, but more type-safe and secure.
Example:public delegate int PerformCalculation(int x, int y);
Why to Use Deligate
Delegates are used when you want to treat methods as first-class objects — i.e., pass methods around like variables, store them, invoke them later, or call different methods dynamically. This allows for loose coupling, flexibility, and dynamic behavior, which direct method calls don’t provide. Let's break it down:
Flexibility (Dynamic Behavior)
You can change the method being called at runtime by assigning a different method to the delegate. This allows your code to be more flexible and reusable.: MyDelegate del;
if (condition)
del = DoSomething;
else
del = DoSomethingElse;
del(); // Will call different methods depending on condition
Callback Mechanism
Delegates allow you to pass methods as parameters and enable callbacks. This is impossible with just direct method calls unless you hard-code everything. void ProcessData(int x, MyDelegate callback)
{
// do something
callback();
}
Decoupling / Loose Coupling
Delegates help separate components of your application.For example:
- A button click handler in a UI can be wired to different logic without changing the button code.
- In event-driven systems (like UI or networking), delegates keep systems decoupled.
Invoke multiple methods
Delegates can call multiple methods (multicast): MyDelegate del = MethodA;
del += MethodB;
del(); // Calls both MethodA and MethodB
Declaring a Delegate in C#
In C#, a delegate is declared using the delegate keyword. The declaration defines the method signature (return type + parameters) that any method assigned to the delegate must match.
Syntax: delegate return_type DelegateName(parameter_list);
Example:
// Declare a delegate that takes two integers and returns an integer
public delegate int MathOperation(int x, int y);
This MathOperation
delegate can point to any method that:
- Returns an
int
- Takes two
int
parameters
public static int Add(int a, int b)
{
return a + b;
}
public static int Multiply(int a, int b)
{
return a * b;
}
There are three main types of delegates in C#:
- Single-cast Delegate
- Refers to one method at a time.
- Most common type of delegate.
- If you assign a method to a delegate, it overwrites the previous method.
- Multicast Delegate
- Can refer to multiple methods.
- Uses
+=
and-=
operators to add/remove method references. - All methods are called in sequence when the delegate is invoked.
- Only the return value of the last method is returned (if it has a return type).
- Generic Delegates C# includes three built-in generic delegate types which we will descuss this later in another post.
- Func
<>
- Action
<>
- Predicate
<>
- Func
Console Application: Delegate Demo
We'll create a console application that performs different operations (Add, Subtract, Multiply) using delegates.
using System;
namespace DelegateExample
{
// Step 1: Declare a delegate
public delegate int MathOperation(int a, int b);
class Program
{
// Step 2: Define methods that match the delegate signature
public static int Add(int x, int y)
{
return x + y;
}
public static int Subtract(int x, int y)
{
return x - y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
static void Main(string[] args)
{
// Step 3: Instantiate the delegate and assign methods
MathOperation op;
Console.WriteLine("Enter two numbers:");
Console.Write("Number 1: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Number 2: ");
int b = int.Parse(Console.ReadLine());
Console.WriteLine("\nChoose operation: 1. Add 2. Subtract 3. Multiply");
string choice = Console.ReadLine();
// Step 4: Point delegate to the chosen method
switch (choice)
{
case "1":
op = Add;
break;
case "2":
op = Subtract;
break;
case "3":
op = Multiply;
break;
default:
Console.WriteLine("Invalid choice.");
return;
}
// Step 5: Invoke the delegate
int result = op(a, b);
Console.WriteLine($"\nResult: {result}");
}
}
}
Summary
Understanding delegates is essential for mastering C#'s event-driven and functional programming capabilities. I hope this was helpful to you.
Thanks