Introduction to Delegates
What are Delegates?
Delegates in C# are similar to function pointers in C/C++, but they are type-safe. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are used to pass methods as arguments to other methods. Event handling in C# is based on delegates.
Declaring and Using Delegates
To declare a delegate, you use the delegate keyword. Below is the syntax for declaring a delegate:
public delegate void MyDelegate(string msg);
In this example, MyDelegate can be used to reference any method that has a void return type and takes a single string parameter.
Creating a Delegate Instance
First, let's create a method that matches the delegate signature:
public void DelegateMethod(string message)
{
Console.WriteLine(message);
}
Now, we can create a delegate instance and assign the method to it:
MyDelegate del = new MyDelegate(DelegateMethod);
Or simply:
MyDelegate del = DelegateMethod;
Invoking Delegates
Once a delegate is assigned a method, it behaves exactly like that method. The delegate can be invoked like this:
del("Hello, World!");
This will call the DelegateMethod and output:
Multicast Delegates
A delegate can call more than one method when invoked. This is known as a multicast delegate. Methods can be added to or removed from the delegate using the + and - operators. For example:
MyDelegate del1 = DelegateMethod1;
MyDelegate del2 = DelegateMethod2;
MyDelegate del3 = del1 + del2;
del3("Hello, World!");
In this example, both DelegateMethod1 and DelegateMethod2 will be called when del3 is invoked.
Real-world Example
Delegates are often used in designing extensible and flexible applications (e.g., implementing callback methods, event handling). Here's a simple example of using delegates for event handling:
public class Program
{
public delegate void Notify(string message);
public class ProcessBusinessLogic
{
public event Notify ProcessCompleted;
public void StartProcess()
{
Console.WriteLine("Process Started!");
// Some code here...
OnProcessCompleted("Process Completed!");
}
protected virtual void OnProcessCompleted(string message)
{
ProcessCompleted?.Invoke(message);
}
}
public static void Main(string[] args)
{
ProcessBusinessLogic bl = new ProcessBusinessLogic();
bl.ProcessCompleted += Bl_ProcessCompleted;
bl.StartProcess();
}
public static void Bl_ProcessCompleted(string message)
{
Console.WriteLine(message);
}
}
In this example, when the StartProcess method is called, it triggers the ProcessCompleted event, which in turn calls the Bl_ProcessCompleted method.
