In C#, a delegate is a type-safe function pointer that allows methods to be referenced and invoked dynamically. It provides a way to treat methods as objects, enabling scenarios such as event handling, callbacks and functional-style programming.
Key Points
- A delegate defines the signature of methods it can point to.
- It can reference both static and instance methods.
- Delegates are type-safe, meaning the method signature must match the delegate declaration.
- They are the foundation of events and anonymous functions in C#.
When to Use Delegates
- For implementing callbacks.
- For handling events.
- For writing flexible, reusable code where behavior can be passed as parameters.
- For functional-style programming with LINQ and lambdas.
Declaration of Delegates
Delegate type can be declared using the delegate keyword. Once a delegate is declared, delegate instance will refer and call those methods whose return type and parameter-list matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name]([parameter_list]);
- modifier: Defines the accessibility of the delegate (public, private, internal, etc.). It is optional.
- delegate: The keyword used to declare a delegate.
- return_type: The type of value returned by the methods referenced by the delegate (can also be void).
- delegate_name: The identifier you assign to the delegate.
- parameter_list: Defines the parameters the delegate requires. The methods assigned must match this list exactly.
Example:
C#
using System;
public class DelegateExample
{
// Delegate declaration
public delegate void MyDelegate(string message);
// Method matching the delegate signature
public static void DisplayMessage(string msg)
{
Console.WriteLine("Message: " + msg);
}
public static void Main()
{
// Instantiating delegate
MyDelegate del = DisplayMessage;
// Invoking delegate
del("Hello from delegate!");
}
}
OutputMessage: Hello from delegate!
Explanation:
- MyDelegate is defined to point to methods that take a string parameter and return void.
- The DisplayMessage method matches the delegate signature.
- The delegate instance del references the method and is invoked like a method call.
Multicasting of a Delegate
Delegates can reference multiple methods at once using the + or += operator. Such delegates are called multicast delegates.
Properties:
- Delegates are combined and when you call a delegate then a complete list of methods is called.
- All methods are called in First in First Out(FIFO) order.
- '+' or '+=' Operator is used to add the methods to delegates.
- '–' or '-=' Operator is used to remove the methods from the delegates list.
CSharp
using System;
public class MulticastDelegateDemo
{
public delegate void Notify();
public static void MethodA() => Console.WriteLine("Method A executed");
public static void MethodB() => Console.WriteLine("Method B executed");
public static void Main()
{
Notify notify = MethodA;
notify += MethodB;
notify(); // Invokes both MethodA and MethodB
}
}
OutputMethod A executed
Method B executed
Note:
If the delegate has a return value, only the result of the last method in the invocation list is returned.
Delegates with Return Types
Delegates can also be used with methods that return values.
C#
using System;
public class ReturnDelegateDemo
{
public delegate int Operation(int x, int y);
public static int Add(int a, int b) => a + b;
public static int Multiply(int a, int b) => a * b;
public static void Main()
{
Operation op = Add;
Console.WriteLine("Addition: " + op(5, 3));
op = Multiply;
Console.WriteLine("Multiplication: " + op(5, 3));
}
}
OutputAddition: 8
Multiplication: 15
Explanation:
- Delegates can point to methods that return a value and the return type must match the delegate signature.
- If multiple methods are attached, only the last method’s return value is returned.
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers