Curriculum
In C#, a delegate is a type that represents a reference to a method. It allows a method to be treated as an object, which can be passed around and stored like any other value. Delegates are often used to define callback functions or to implement event handling in C# applications.
Delegates are declared using the delegate keyword, followed by the return type and parameter list of the method that the delegate will refer to. Here’s an example of a delegate declaration:
delegate int CalculationDelegate(int a, int b);
This declares a delegate named CalculationDelegate that takes two int parameters and returns an int value. The delegate can be used to refer to any method that has the same signature, meaning that it takes two int parameters and returns an int value.
Here’s an example that shows how to use a delegate to perform a calculation:
using System;
delegate int CalculationDelegate(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static int Subtract(int a, int b)
{
return a - b;
}
static void Main(string[] args)
{
CalculationDelegate calc;
calc = new CalculationDelegate(Add);
int sum = calc(10, 5);
Console.WriteLine("10 + 5 = {0}", sum);
calc = new CalculationDelegate(Subtract);
int difference = calc(10, 5);
Console.WriteLine("10 - 5 = {0}", difference);
Console.ReadKey();
}
}
In this example, we define two methods, Add and Subtract, that take two int parameters and return an int value. We then declare a delegate named CalculationDelegate that matches the signature of these two methods.
In the Main method, we create an instance of the delegate and assign it to the Add method. We then use the delegate to call the Add method, passing in two integer arguments. The result is stored in the sum variable and displayed on the console.
We then reassign the delegate to the Subtract method and use it to call the Subtract method with the same arguments. The result is stored in the difference variable and displayed on the console.
The output of this program will be:
10 + 5 = 15 10 - 5 = 5
Delegates can also be used to implement event handling in C#. Here’s an example that demonstrates how to define and use an event with a delegate:
using System;
delegate void EventHandler();
class Button
{
public event EventHandler Click;
public void OnClick()
{
if (Click != null)
{
Click();
}
}
}
class Program
{
static void Main(string[] args)
{
Button button = new Button();
button.Click += new EventHandler(OnButtonClick);
button.OnClick();
Console.ReadKey();
}
static void OnButtonClick()
{
Console.WriteLine("Button clicked!");
}
}
In this example, we define a Button class that has an event named Click. The event is declared using a delegate of type EventHandler, which has a void return type and takes no parameters. We also define a method named OnClick that raises the Click event.
In the Main method, we create a Button object and add an event handler to its Click event. We then call the OnClick method of the button object, which raises the Click event and invokes the event handler that we registered.
When the Click event is raised, the OnButtonClick method is called, which simply displays a message on the console.
The output of this program will be:
Button clicked!
Delegates can be useful in a wide variety of scenarios, such as implementing callbacks, defining event handlers, and decoupling application components. They allow methods to be treated as objects, making it possible to pass them around as parameters or store them as values.
Some of the commonly used methods of delegates in C# are:
Delegate.Combine: Combines two delegates into a new delegate that invokes both delegates in the order in which they are passed.Delegate.Remove: Removes the second delegate from the invocation list of the first delegate.Delegate.GetInvocationList: Returns an array of delegates that make up the invocation list of the current delegate.Here’s an example that demonstrates how to use these methods:
using System;
delegate void EventHandler();
class Program
{
static void Main(string[] args)
{
EventHandler handler1 = new EventHandler(Method1);
EventHandler handler2 = new EventHandler(Method2);
// Combine two delegates
EventHandler combined = (EventHandler)Delegate.Combine(handler1, handler2);
combined();
// Remove second delegate
combined = (EventHandler)Delegate.Remove(combined, handler2);
combined();
// Get invocation list
Delegate[] invocationList = combined.GetInvocationList();
foreach (Delegate d in invocationList)
{
d.DynamicInvoke();
}
Console.ReadKey();
}
static void Method1()
{
Console.WriteLine("Method1");
}
static void Method2()
{
Console.WriteLine("Method2");
}
}
In this example, we define two methods, Method1 and Method2, that take no parameters and return void. We then declare two delegate instances, handler1 and handler2, that refer to these methods.
We use the Delegate.Combine method to combine the two delegates into a new delegate named combined, and then call the delegate to execute both methods.
We then use the Delegate.Remove method to remove the handler2 delegate from the combined delegate. We call the combined delegate again to show that only Method1 is executed.
Finally, we use the Delegate.GetInvocationList method to obtain an array of delegates that make up the invocation list of the combined delegate. We use a foreach loop to iterate over this array and call each delegate in turn.
The output of this program will be:
Method1 Method1