Delegate in C# - CloudFronts

Delegate in C#

In this blog we will be explaining you about Delegate in C# and types of delegate.

In simple terms, C# has a data type that allows developers to pass methods as parameters of other methods. This data type is called a delegate.

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance. A delegate is a references type that invokes single/multiple method(s) through the delegate instance. It holds a reference of the methods. Delegate types are sealed and immutable type.

A useful property of delegate objects is that they can be composed using the “+” operator. A composed delegate calls the two delegates it was composed from. Only delegates of the same type can be composed. The “-” operator can be used to remove a component delegate from a composed delegate.

When you instantiate a delegate by using a named method, the method is passed as a parameter. Delegates constructed with a named method can encapsulate either a static method or an instance method. Named methods are the only way to instantiate a delegate in earlier versions of C#. Concept of Anonymous method was introduced in C# ver. 2.0, where you can pass code block as a parameters to separately defined method. C# ver. 3.0 introduced lambda expressions as a more crisp way of writing inline code blocks. Both anonymous methods and lambda are compiled to delegate types. Together, these features are now known as anonymous functions.

In C# ver. 1.0 and later, delegates can be declared as shown below.

// Declare a delegate. 
delegate void Del(string str);

// Declare a method with the same signature as the delegate. 
static void Notify(string name)
{
    Console.WriteLine("Notification received for: {0}", name);
}
// Create an instance of the delegate.
Del del1 = new Del(Notify);

In C# ver. 2.0 and later, it is also possible to use an anonymous method to declare and initialize a delegate, as shown below.

Del del2 = delegate(string name)
{ 
Console.WriteLine("Notification received for: {0}", name);
 };

In C# ver. 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown below.

Del del3 = name =>  { Console.WriteLine("Notification received for: {0}", name); };

Use of Delegate

  1. Abstract and encapsulate a method: – This is the most important use of delegates, it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods.
    2. Asynchronous processing: – By using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously.
    3. Multicasting (Sequential processing): –Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate.

Delegates are useful when:

  1. The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
  2. When a class may want to have multiple implementations of the method specification.
  3. It is desirable to allow using a static method to implement the specification.
  4. The provider of the implementation wants to “hand out” the implementation of the specification to only a few select components.

Types of Delegate

There are three types of delegates that can be used in C#.

Single cast Delegate: – Single cast delegate means which hold address of single method. In the single cast delegate signature of delegate should be same as method for which we are creating this delegate.

Multi cast Delegate: – Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use “+=” operator and if you want remove addresses from delegate we need to use “-=“operator. Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list.

Generic Delegate: – Generic Delegates was introduced in Framework 3.5, a generic delegate can define its own type parameters. Code that references the generic delegate can specify the type argument to create a closed constructed type, just like when instantiating a generic class or calling a generic method. Generic Delegates are especially useful in defining events based on the typical design pattern because the sender argument can be strongly typed and no longer has to be cast to and from Object.

Delegate in a nutshell

  1. Delegates are similar to the function pointer in C and C++, difference between the function pointer and delegate is that delegates are type safe. Delegates are objects that contain information about the function rather than data. We can encapsulate a reference to the method inside the delegate object.
  2. Delegates provide a simple way of representing a method call, potentially with a target object, as a piece of data which can be passed around.
  3. It is not necessary to use delegation with parameters, we can use delegates with and without parameters.
  4. We can use static or non-static function, in case of static function we encapsulate the function with class name and in the case of a non-static function we first make the object of the class and then we use a function with the object.

 


Share Story :

Secured By miniOrange