Thursday, 29 December 2011

Simple Delegate in C#

Delegates roughly similar to function pointers in C++.
A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature and can be used later.

How to use

The type safety of delegates requires the function you pass as a delegate to have the same signature as the delegate declaration.

See the fallowing program for more information on using delegates.



namespace delegates
{
//Create a new category

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

public class MyDelegateProgram
{
public static int FunAdd(int x, int y)
{
return x + y;
}
public static int FunMultiply(int x, int y)
{
return x * y;
}
}

class Program
{
static void Main(string[] args)
{
//instance and initialization
MyDelegate DelAdd = new MyDelegate(MyDelegateProgram.FunAdd);
MyDelegate DelMul = new MyDelegate(MyDelegateProgram.FunMultiply);
//invoking function using delegates
Console.WriteLine("Addition : " + DelAdd(4, 5));
Console.WriteLine("Multiplication : " + DelMul(4, 5));
//array of Delegates-----------
Console.WriteLine("Using Array of Delegate");
MyDelegate[] arrDelegates;
arrDelegates = new MyDelegate[2]; //size of delegate array
arrDelegates[0] = new MyDelegate(MyDelegateProgram.FunAdd);
arrDelegates[1] = new MyDelegate(MyDelegateProgram.FunMultiply);
foreach (MyDelegate item in arrDelegates)
{
Console.WriteLine(item(4, 5));
}
Console.ReadKey();
}
}
}

No comments:

Post a Comment