Home > Asp.net > What is delegate, when to use and it’s types in c#

What is delegate, when to use and it’s types in c#

This post was most recently updated on April 25th, 2019

What is delegate?

  • It is reference to a method inside delegate object
  • User defined type
  • It is  not member of class but similar to class

When to use delegate?

  • Represent or refer more than one functions
  • Used to define call back methods
  • In order to use delegate it is necessary to create an object to delegate

Types of delegate?

  1. Single cast delegate: represents or refer only one function
  2. Multicast delegate: represents or refer more than one function

Steps in working with delegate:

  1. Creating a delegate
  2. Instantiating a delegate
  3. Invoking a delegate

Creating a delegate:

Syntax

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

Public delegate void Delegate (int x, int y);

Note: While creating delegate its return type,number of arguments and its data types should be same as function that we want to refer to.

e.g

If we want to use delegate to refer above function then it should be declared like: 

Example of single cast delegate: 

Multi cast delegate:

In multi cast delegate to add reference to more than one function use operator (+=)

And to remove the reference of any  function from delegate object use operator (-=)

Example of Multi cast delegate:

o/p of above code:

 

This Article is TAGGED in . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">