C# Delegates
A delegate is a type that holds a reference to a method. A delegate variable can call the method it holds.
A delegate holds a method
Operation declares two int inputs and an int result. The variable holds the Add method.
using System;
delegate int Operation(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Operation op = Add;
Console.WriteLine(op(3, 4));
}
}Reassigning the delegate
The variable first holds Add. It then holds Multiply instead.
using System;
delegate int Operation(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static int Multiply(int a, int b)
{
return a * b;
}
static void Main(string[] args)
{
Operation op = Add;
Console.WriteLine(op(3, 4));
op = Multiply;
Console.WriteLine(op(3, 4));
}
}A multicast delegate
The += operator adds a second printer. Both printers run in the order they were added.
using System;
delegate void Printer(string text);
class Program
{
static void PrintFirst(string text)
{
Console.WriteLine("First: " + text);
}
static void PrintSecond(string text)
{
Console.WriteLine("Second: " + text);
}
static void Main(string[] args)
{
Printer printer = PrintFirst;
printer += PrintSecond;
printer("go");
}
}Example
using System;
delegate int Transform(int n);
class Program
{
static int Square(int n)
{
return n * n;
}
static int Double(int n)
{
return n + n;
}
static void Main(string[] args)
{
Transform change = Square;
Console.WriteLine(change(5));
change = Double;
Console.WriteLine(change(5));
}
}Key points
- A delegate type declares a method signature.
- A delegate variable holds a method with that signature.
- Assigning a new method changes what the variable calls.
- The += operator adds another method to a delegate variable.
- A combined delegate calls its methods in the order they were added.
In this example, the Transform variable first holds Square. Calling it with 5 prints 25. The variable then holds Double, and the same call prints 10.
Note
The delegate type must match the method signature exactly.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
After op = Multiply, what does op(3, 4) print?