Delegates in C#
Posted by Superadmin on August 14 2022 03:51:21

Delegates in C#

 

 

A delegate is a type of variable that can hold a reference to a method or an object that references a method. In C#, delegate functions are equivalent to function pointers in C/C++ and also provide a way to specify which method to call when an event occurs. Delegate is a library class in the System namespace. Delegates are most commonly used to implement callback methods and events. A delegate can also be used to call an anonymous method and lambda expressions.

 

 

There are three stages to follow while working with delegates:

Delegate Syntax:

Declaration of a delegate is done by using the delegate keyword followed by a function signature, as indicated below.

[access modifier] delegate [return type] [delegate name]([parameter list]);

Types of Delegates:

 

In C#, there are three different types of delegates.

Singlecast Delegate

Single Cast Delegate is a delegate type that can only refer to one method at a time. It derives from the System.Delegate class.

 

 

Multicast Delegate

The multicast delegate can be used to call multiple methods at the same time. The “+” operator adds a function to the call list, and the “-” operators remove it.

 

 

Generic Delegate

The delegate instance does not need to be defined to use the Generic Delegates methods. There are three types of generic delegates: Func, Action, and Predicate.