Tuesday, April 8, 2014

Delegates in C#.NET

 

Introduction

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to 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. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

Syntax for declaring the delegates:

delegate <return type> <delegate-name> <parameter list>

Example:

public delegate int MyDelegate (string s);


Using delegates in a c# program:

delegate int NumberChanger(int n);
namespace DelegateAppl
{   
class TestDelegate   
{
static int num = 10;      
public static int AddNum(int p)      
{         
num += p;         
return num;      
}      
public static int MultNum(int q)      
{
num *= q;         
return num;      
}      
public static int getNum()      
{         
return num;      
}      
static void Main(string[] args)      
{         
//create delegate instances         
NumberChanger nc1 = new NumberChanger(AddNum);         
NumberChanger nc2 = new NumberChanger(MultNum);         
//calling the methods using the delegate objects         
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());         
nc2(5);         
Console.WriteLine("Value of Num: {0}", getNum());         
Console.ReadKey();      
}
}
} 

No comments:

Post a Comment