Delegates

A delegate is a reference type used to encapsulate a method with a specific signature and return type. Simply it’s a reference type to method.

In C++ and many other languages, we can use this requirement with function pointers and pointers to member functions. Unlike function pointers, delegates are object-oriented and type-safe

A delegate is created with the delegate keyword, followed by a return type and the signature of the methods that can be delegated to it, as in the following:

public delegate int MyDelegate(object obj1, object obj2);

Simple Example:

  1. Create a new Windows application in VS 2008.
  2. Add code file and enter the Delegate definition

Commonly Delegates are defined in code file

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

  1. Add New class called Calculator tat contain Add(),Sub(), Mul(), Div().


class Calculator
{
public int Add(int x, int y)
{
return (x + y);
}
public int Sub(int x, int y)
{
return (x – y);
}
public int Mul(int x, int y)
{
return (x * y);
}
public int Div(int x, int y)
{
return (x / y);
}
}

  1. Add one Button named Delegate to the form and enter the give code

private void Delegate_Click(object sender, EventArgs e)

{

Calculator calc = new Calculator();

MyCalcDelegate del = new MyCalcDelegate (calc.Add);

int sum = del(10, 5);

del += new MyAreaDelegates(calc.Sub);

del += new MyAreaDelegates(calc.Mul);

del += new MyAreaDelegates(calc.Div);

Console.WriteLine(“Result:”+sum);

}

Change the Debugging properties as Console Application and run the application

Now you can see only result for Add().

If we want to call all methods in delegates, we must invoke “MulticastDelegate”

Multicast Delegate having the Invocation list. That Invocation list obtain by calling the method getInvocation().

We can modify the above coding as follow as

private void Delegate_Click(object sender, EventArgs e)

{

Calculator calc = new Calculator();

MyCalcDelegate del = new MyCalcDelegate (calc.Add);

del += new MyAreaDelegates(calc.Sub);

del += new MyAreaDelegates(calc.Mul);

del += new MyAreaDelegates(calc.Div);

Delegate[] myDel=del.GetInvocationList();

foreach(del d in myDel)

{

Int re=d(10,5);

Console.WriteLine(“Result is:”+re);

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: