Delegate and events concept in C#.Net, WebApi and MVC.




  •  A delegate is a reference type that holds the reference of a method. Any method which has the same signature as delegate can be assigned to delegate. It is very similar to the function pointer but with a difference that delegates are a type safe. We can say that it is the object-oriented implementation of function pointers.

  •  Delegates are used in event handling for defining call back methods.

  •  Delegates can be chained together i.e. these allow defining a set of methods that executed as a single unit.

  • Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.

  • All delegates are implicitly derived from System.MulticastDelegate, which is inheriting from System.Delegate class.

  • Delegates provide a way to execute methods at run-time.

  • Delegates can call methods synchronously and asynchronously.

Types of delegates:

Single cast delegate:

A single cast delegate holds the reference of only single method. In previous example, created delegate is a single cast delegate.

Multi cast delegate:

A delegate which holds the reference of more than one method is called multi-cast delegate. A multicast delegate only contains the reference of methods which return type is void. The + and += operators are used to combine delegate instances. Multicast delegates are considered equal if they reference the same methods in the same order.

Declaration format:

public delegate int operation(int x, int y);   

Why do we need delegate?

     A delegate is a solution for situations in which you want to pass methods around to other methods. 
-      When we need to call any method at run time, we can use delegate. It calls method pass by ref so if we call multiple methods which are using same variable, in this case variable holds its value and we get the most updated value of variable.

Example:
using System;

delegate int NumberChanger(int n);
namespace DelegateAppl {
  
   class TestDelegate {
      static int num = 10;
     
      public static int AddNum(int p) {
         num += p;
         return num;
      }
      public static int MultNum(int q) {
         num *= q;
         return num;
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
        
         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

Output:
Value of Num: 35
Value of Num: 175


Comments

Post a Comment