Hello Friends, In this tutorial we are going to learn Delegate in C#. A delegate is similar to a pointer in C++.  Let’s discuss it in detail with the example.

After Completing this tutorial you will be able to understand:

  • What is Delegate in C#?
  • Types of Delegate in C#?
  • Advantages of Delegate?

What is Delegate?

A delegate is a reference type Data Type that allows the programmer to encapsulates the reference to the method inside a Delegate object. A delegate is similar to Pointer to C and C++. The method that referenced the Delegate should have the same signature as that of Deleage.

Features of Delegate:

  1. A delegate is similar to Function Pointer in C++ but they are type safe.
  2. A delegate takes method as a parameter.
  3. A delegate can be used to define Callback method.
  4.  A delegate can be used as an Anonymous method. Anonymous methods are methods without method name and that contains inline code.
  5. Advantages of Delegate:
  6. Delegate hide the method call’s from the user.
  7. Effective use of Delegate can increase the performance of the application.
  8. Delegate used to call a method asynchronously.

There are few steps of using Delegate:

Step 1- Instantiating Delegate:

Syntax:

Example:

While declaring a delegate the access modifier, return type and the number of arguments and data type should be same.

Step 2- Instantiating a Delegate:

Syntax:

Example:

Consider a Function:

Step 3- Invoking a Delegate:

Syntax:

Example:

Types of Delegate:

1-Single Cast Delegate:

Single Cast Delegate holds the reference of only one method.

An example of Single Cast Delegate:

Create a Console Application called SingleCastDelegateDemo.

Delegate

Open Program.cs file and write the following code.

Run the application and look over the output window:

Delegate

2- Multicast Delegate:

 Multicast Delegate holds the reference of multiple method.

An example of Multicast Delegate:

Delegate

Open Program.cs file and write the following code.

In the above example, you can see we have added the reference to multiple methods using += operator. You can also remove reference to the method using -=.

Run the application and look over the output window.

Delegate

Conclusion:

I hope you are more clear about Delegate. I would like to have your Comments, Suggestions and Feedback.

View More:

Thank You.

Leave a Comment