Tuesday, May 10, 2011

What is Delegates ?

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

Delegates also can invoke methods Asynchronously.

A delegate type maintains three important pices of information :

The name of the method on which it make calls.
Any argument (if any) of this method.
The return value (if any) of this method.
Defining a Delegate in C#

when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer.

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

A Delegate Usage Example

namespace MyFirstDelegate
{
//This delegate can point to any method,
//taking two integers and returning an
//integer.
public delegate int MyDelegate(int x, int y);
//This class contains methods that MyDelegate will point to.
public class MyClass
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
class Program
{
static void Main(string[] args)
{
//Create an Instance of MyDelegate
//that points to MyClass.Add().
MyDelegate del1 = new MyDelegate(MyClass.Add);
//Invoke Add() method using the delegate.
int addResult = del1(5, 5);
Console.WriteLine("5 + 5 = {0}\n", addResult);
//Create an Instance of MyDelegate
//that points to MyClass.Multiply().
MyDelegate del2 = new MyDelegate(MyClass.Multiply);
//Invoke Multiply() method using the delegate.
int multiplyResult = del2(5, 5);
Console.WriteLine("5 X 5 = {0}", multiplyResult);
Console.ReadLine();
}
}
}

No comments:

Post a Comment