Saturday, February 4, 2012

What are Delegates?



A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners. It encapsulates a reference of a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Basically it is similar like the old "C" age function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns.

At first, a delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. The function will then can be called via the delegate object.



Syntax :


delegate result-type identifier ([parameters]);

where:
  1. result-type: The result type, which matches the return type of the function.
  2. identifier: The delegate name.
  3. parameters: The Parameters, that the function takes.

Example :

 public delegate void SimpleDelegate ()




 1. Defining the delegate

public delegate int Calculate (int value1, int value2);

 2. Creating methods which will be assigned to delegate object

class deletageClassExample
{
public int add(int value1, int value2)
{
    return value1 + value2;            
}

public int sub( int value1, int value2)
{
    return value1 - value2;            
}


public int mul( int value1, int value2)
{
    return value1 * value2;            
}


public int div( int value1, int value2)
{
    if(value>0)
    return value1 / value2;
    return
0;            
}

}

 3. Create the delegate object and assigning methods to those delegate objects

 deletageClassExample delclass = new  deletageClassExample  ();

Calculate add = new Calculate( delclass .add);
Calculate sub = new Calculate( delclass .sub);
Calculate mul= new Calculate( delclass .mul);
Calculate div= new Calculate( delclass .div);


4. Call the methods via delegate objects

//using the delegate objects to call the assigned methods 
Console.WriteLine("Adding two values: " +        add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));
Console.WriteLine("Subtracting two values: " + sub(10,4));
Console.WriteLine("Subtracting two values: " + sub(10,4));




See Some Videos :














No comments:

Post a Comment

Live

Your Ad Here