Delegates are same are function pointers in C++, but the only difference is that they are type safe, unlike function pointers.

Delegates are required because they can be used to write much more generic type-safe functions.

A delegate is a type that represents references to methods.

When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.


Code Snippet:


public delegate void Del(string message);

// Create a method 1 for a delegate. 
public static void DelegateMethod_1(string message)

// Create a method 2 for a delegate. 
public static void DelegateMethod_2(string message)
  System.Console.WriteLine(message+" !!!");

// Instantiate the delegate for method 1.
Del handler = DelegateMethod_1;
// Call the delegate.
handler("Hello World");
//output: Hello World

// Instantiate the delegate for method 2.
Del handler = DelegateMethod_2;
// Call the delegate.
handler("Hello World");
//output: Hello World !!!


Programming Scenario:

If we want to execute methods at runtime based on usage then in that situation we can use Delegate.

For Example:

Consider you want to build control preference selector and based on its usage/ where this control is used. we want to save data in different databases.

In this situation will write control to accept/configure name of method which used to save data based on usage/databases where you want to save data.

Once we have function name which should be invoked then will use Delegate to point to configured method. Whenever this is any action on delegate for updating data it will invoke method pointed.