Sunday, February 16, 2014

C# - Delegates

What is Delegates?
In a simple language, as we use in C and C++, a pointer which points to the functions. In C# there is no pointer, but delegates are working as a pointer to function.
A delegate is a reference type variable that holds the reference to a method. The reference can be changed at run-time.

Use of Delegates
When we want to use functionality of Events and Call-backs at that time delegates comes to the picture.
Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.

Declaration of Delegates
Declaration of delegates determines the methods that can be referenced by the delegate.
All methods which are refers to delegate must have same signature as delegate.


          delegate   <return type>   <delegate-name>    <parameter list>
public    delegate       int            MyDelegate         (string s);

Example
 

using System;

delegate int Calc(int n);
namespace DelegateAppl
{
   class TestDelegate
   {
      static int num = 0;
      public static int AddNum(int p, int q)
      {
         num = p + q;
         return num;
      }

      public static int MultNum(int p, int q)
      {
         num = p * q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }

      static void Main(string[] args)
      {
         //create delegate instances
         Calc c1 = new Calc(AddNum);
         Calc c2 = new Calc(MultNum);
         //calling the methods using the delegate objects
         c1(25,30);
         Console.WriteLine("Value of Num: {0}", getNum());
         c2(5,6);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}


Output:
Value of Num: 55
Value of Num: 30
  



0 comments:

Post a Comment

Freemarket.com Marketplace