A delegate in C# is like a pointer to a method that allow you to pass methods as parameters, store methods for later execution. When you use a delegate, you can call a method indirectly, or even change the method it calls during runtime.
Syntax:
public delegate returnType DelegateName(parameterType parameterList);
Example of Delegate
There are many steps to define Delegate
Step 1: Declare a Delegate
We’ll declare a delegate called MyDelegate that will point to any method that takes a string as input and returns string.
public delegate string MyDelegate(string message);
This delegate can now hold references to methods that match this signature (methods that take a string and return string).
Explanation:
We declare a delegate type MyDelegate that represents any method that takes a string parameter and returns string.
Step 2: Create a Method that Matches the Delegate’s Signature
We’ll create a method that matches the delegate’s signature.
public static string printMessage(string message)
{
return message;
}
Explanation:
We define a method printMessage that matches the signature of the delegate.
Step 3: Instantiate the Delegate and Call the Method
Now we create an instance of the delegate and point it to the PrintMessage method.
public static void Main()
{
// create an instance of delegate by passing method name
MyDelegate myDelegate = new MyDelegate(printMessage);
// calling printMessage() using delegate
string result = myDelegate("Hello World!");
Console.WriteLine(result);
}
Explanation:
In the Main method, we create an instance of the delegate, pointing it to myDelegate. We then invoke the delegate as if it were a method.
Complete Example:
using System;
using System.Collections.Generic;
class MyProgram
{
public static string printMessage(string message)
{
return message;
}
// define a delegate
public delegate string MyDelegate(string message);
static void Main()
{
// create an instance of delegate by passing method name
MyDelegate myDelegate = new MyDelegate(printMessage);
// calling printMessage() using delegate
string result = myDelegate("Hello World!");
Console.WriteLine(result);
}
}
Output:
Why Use Delegates?
1. Decoupling: Delegates allow you to separate the definition of the method from the place where it’s executed. This makes the code easier to maintain and extend.
2. Event Handling: Delegates are often used in event-driven programming (e.g., in UI applications).
3. Callback Methods: Delegates can be used to implement callback patterns, where you pass a method to another method to be invoked later.