C# Delegates
What is Delegates ?

- A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
- Delegate is a function pointer. It holds the reference of one or more methods at runtime.
- A delegate can be passed as a method parameter.
- The delegate is a reference type data type that defines the method signature that is return type and parameter list types. You can define variables of delegate, just like other data type, that can refer to any method with the same signature as the delegate.
Necessity of Delegates
What if we want to pass a function as a parameter? How does C# handles the callback functions or event handler? The answer is – delegate.
How Delegates Work
There are three steps involved while working with delegates:
- Declare a delegate
- Set a target method
- Invoke a delegate
After declaring a delegate, we need to set the target method or a lambda expression. We can do it by creating an object of the delegate using the new keyword and passing a method whose signature matches the delegate signature.

Example-1: Simple Delegate
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegateExample { // Declaration public delegate void SimpleDelegate(); class Program { public static void MyFunc() { Console.WriteLine("I was called by delegate ..."); } static void Main(string[] args) { // Instantiation SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc); // Invocation simpleDelegate(); } } }