Day 16-Delegates

Delegates can be used to hold the reference of method. A delegate is a type that safety encapsulates a method and it is similar to function pointer in C and C++. Delegates can be used to define call back methods. Delegate class hold only those methods which have same signature. It allow methods to be passed as parameters. A delegate can be seen as a placeholder for method.

Delegates can be chained multiple methods together and can be called on a single event.

Suppose if you have multiple methods with same signature which have same return type & number of parameters and want to call all the methods with single object then we can go for delegates.

Creating and using delegates involve the four steps:

1. Declaring a delegates

2. Defining a delegate method

3. Creating delegate object

4. Invoking delegate object


Types of Delegates

1. Single cast delegate

Delegate that represent only a single method is known as Single Cast Delegate.
 

2. Multi Cast Delegate

Delegate that represent more than one method is known as Multi Cast Delegate.

Use += operator to add reference of more method to delegate

Use -= operator to remove reference of a method
 


Click To Zoom Image

Click To Zoom Image