Saturday, 21 January 2012

Delegate in c# .net



Delegate in c#

A delegate in C# is simillar to a FUNCTION POINTER in C or C++. Delgate can be defind as an Object which contains the address of a method. Delegate is a reference type used to encapsulate a method with a speciific signature and return type.

As written in MSDN

” A Delegate is a type that references a method. Once a delegate is assigned a method , it behaves exactly like that method. The Delegate method can be used like any other method with parameter and return value”.

.Net implements the concept of function pointer using Delegates.

Unlike c or c++ function pointer , Delegates are

  1. Type safe
  2. Object Oriented
  3. Secure..
Delegate have following properties

  1. Delegates are simillar to c++ function pointer but it is type safe in nature.
  2. Delegate allow method to pass as an argument.
  3. Delegate can be chained together.
  4. Multiple methods can be called on a single event.
Delegate is a type which safely encapsulates a method. The type of the delegate is defined by name of the delegate. Delegate does not care about class of the object that it references. Any object will do, only matters is that method signature should be the same as of delegate.

Any instance of a given delegate can refer to any instance or static method on any object of any type. Only one condition is there that signature of method matches the signature of delegate.

Mainly Delegate is used by creating first and then making objcet of that.Main Advantage Delegate is effective use of delegate increase performance of application.

Synatx of delegate

Step 1: Decleration

Delgate is getting declared here.
 
Modifer delegate return_type delegate_name ( [Parameter….])

Step 2: Instantitation

Object of delgate is getting created as passing method as argument


Delegate_name delg_object_name = new Delegate_name( method_name);

Here method_name signature must be same as of signature of delegate. 

Step 3: Invocation

Delegate is getting called here.

Delg_object_name([parameter….]);

Delegate Example 1

                  1 using System;
    2 using System.Collections.Generic; 
    3 using System.Linq; 
    4 using System.Text; 
    5 namespace DelgateForNotes 
    6 { 
    7 class Program 
    8 { 
    9  
   10 public delegate int AddDelegate(int num1, int num2); 
   11 static void Main(string[] args) 
   12 { 
   13 AddDelegate funct1= new AddDelegate(Add); 
   14 int k=funct1(7,2); 
   15 Console.WriteLine(” Sumation = {0}”,k); 
   16 Console.Read(); 
   17 } 
   18 public static int Add(int num1, int num2) 
   19 { 
   20 Console.WriteLine(“I am called by Delegate”); 
   21 int sumation; 
   22 sumation= num1+ num2; 
   23 return sumation; 
   24 } 
   25 } 
   26 } 
Output:
I am called by Delegate
Sumation =9
Purpose of above code is to calculate sum of two numbers . Add is a static function to compute sum of two integers. Signature of Add function is same as of signature of delegate. Here delegate is AddDelegate.

 On Breaking the above code in steps

Step1:

Creating Delegate.
public delegate int AddDelegate(int num1, int num2);

 here AddDelegate is name of delegate.
Return type of delegate is int.
Delegate is taking two integer as input parameter.
Access modifer of delegate is Public.
In above signature keyword “delegate” defines signature is of delegate signature.
So delegate AddDelegate can refer any method having two integer parameter and returning one integer value.
Step 2:
 
Making Object of delegate.
AddDelegate funct1= new AddDelegate(Add);
Funct1 is name of the object.
Note: In case of delegate , object of delegate is also called as delegate. So in this case funct1 can be called as delegate.
As constructor of delegate, here a Method (Add) is passed. Signature of Add method and AddDelegate delegate is exactly same.
Add is a static method.
Step 3:

Invoking delegate
int k=funct1(7,2);
 
funct1 is getting called . Here 7, 2 are passed as parameter.
 MultiCast Delegates
  A delegate which wrap up more than one method is called Multicast Delegates. When a multicast delegate is get called, it will successively call each functions in order. Multicast Delegate allow to chain together several functions. These chain functions can be called together when delegate is invoked. Every Delegate type has a built in support for dealing with multiiple handlers. Delegate gets this support by inheriting from the MultiCastDelegate class.
 To work with Multicast Delegate , delegate signature should return void. Otherwise only last method result can be fetched.
 Operators used are

+= this operator is used to add functions in delegate .

-= this operatir is used to remove function from delegate.

Delegate classes
 
System.Delegate
 
The purpose of a single delegate instance is very similar to a method pointer from C++.   However, in C# don’t use method pointers, rather, it save the “metadata” that identifies the target method to call.  System.Delegate contains two critical data elements.  Firstly, it contains an instance of System.Reflection.MethodInfo – in other words, the .NET metadata that enables method invocation using reflection.
 
The second aspect of System.Delegate is the object instance on which the method needs to be invoked.  Given an unlimited number of objects that could support a method that matches the MethodInfo signature, we also need to be able to identify which objects to notify.  The only exception is when the method identified by MethodInfo is static – in which case the object reference stored by System.Delegate is null.
 
System.MulticastDelegate
 
System.MulticastDelegate therefore, adds to delegates the support for notifying multiple subscribers.  This is enabled through System.MulticastDelegate’s containment of another System.MulticastDelegate instance.  On adding a subscriber to a multicast delegate, the MulticastDelegate class creates a new instance of the delegate type, stores the object reference and the method pointer for the added method into the new instance, and adds the new delegate instance as the next item in a list of delegate instances. In effect, the MulticastDelegate class maintains a linked list of delegate objects.
 
Sequential Invocation
 
When invoking the multicast delegate, each delegate instance in the linked list is called sequentially. This sequential invocation, however, leads to problems if the invoked method throws an exception or if the delegate itself returns data.
 
Multicast Delegate Example 1
    1 using System;
    2 
    3 using System.Collections.Generic;
    4 
    5 using System.Linq;
    6 
    7 using System.Text;
    8 
    9 namespace MulticastDelegate1
   10 
   11 {
   12 
   13 class Program
   14  {
   15 
   16 public delegate void showDelegate(string s);
   17 static void Main(string[] args)
   18  {
   19 
   20     showDelegate s = Display;
   21     s += Show;
   22     s(“Hello”);
   23     s(“Scott”);
   24     Console.Read();
   25  }
   26 
   27  public static void Display(string title)
   28  {
   29  Console.WriteLine(title);
   30  }
   31 
   32 public static void Show(string title)
   33  {
   34  Console.WriteLine(title);
   35  }
   36  }
   37  }


Hello
 
Hello
 
Scott
 
Scott
 
In above example showDelegate is a delegate , which can refer any method having return type void and one string as parameter. There are two static user defind functions called Display and Show .

Multicast Delegate Example 2 

    1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5 
    6 namespace MulticastDelegate
    7  {
    8  class MathOperation
    9 
   10 {
   11  public static void MultiplyByTwo(double d)
   12  {
   13 
   14 double res = d*2;
   15 Console.WriteLine(“Multiply: “+res.ToString());
   16  }
   17 
   18 public static void Squre(double e)
   19  {
   20  double res = e * e;
   21  Console.WriteLine(“Square”+res.ToString());
   22  }
   23  }
   24  class NewProgram
   25  {
   26  public delegate void del(double Qr);
   27  static void Main()
   28  {
   29 
   30 
   31 del d = MathOperation.MultiplyByTwo;
   32 
   33 d += MathOperation.Squre;
   34 
   35 Display(d, 2.00);
   36 
   37 Display(d, 9.9);
   38 
   39 
   40 Console.ReadLine();
   41 
   42 
   43 }
   44 
   45 
   46 static void Display(del action, double value)
   47 
   48 {
   49 
   50 Console.WriteLine(“Result = “+ value);
   51  action(value);
   52  }
   53  }
   54 
The above code is implementing multicast delegate . In above code , there is a MathOperationClass , this class is containing two methods . one to double the input parameter and other to make squre of that.
 public delegate void del(double Qr);
 This is delegate decelaration . It will refer method having one double parameter and will return void.
 Display function is taking delegate and double as parameter. This function is displaying the result and calling the delegate.
 Happy Coding
Post a Comment