Sunday, 12 February 2012

Simple / single-cast Delegate explained

Delegate is type that references a method of a given signature [that is for given input and output
parameters]. Namespace is System, referred as “System.Delegate”. Delegates are type safe as you can
refer a method with the signature specified in the declaration of the delegate.

For example:

public double SquareOf(int val)
{
return val * val;
}

public delegate double MyDelegate(int param);
MyDelegate myDel = new MyDelegate(SquareOf);

In the above code we have declared a delegate MyDelegate with input parameter of type int and output
of type double. Using this we can refer any method with input parameter of type int and output type
double.

public delegate double MyDelegate(int param);

We have instantiated the delegate as follows.

MyDelegate myDel = new MyDelegate(SquareOf);

How we will use delegate

namespace ConsoleApp1
{
class Program
{
public static double SquareOf(int val)
{
return val * val;
}

public delegate double MyDelegate(int param); <= Declaration
static void Main(string[] args)
{
MyDelegate myDel = new MyDelegate(SquareOf); <= Instantiation
double res = myDel(15); <= Using of delegate
Console.WriteLine("Square of 15 is :" + res.ToString());
Console.ReadLine();
}

}

}

Output will be: Square of 15 is :225

No comments:

Post a Comment