Monday, May 21, 2007

Delegates

Define Delegates?
A delegate is a type that enables you to store references to functions. Delegates are declared much like functions, but with no function body and using the delegate keyword.

How is the delegate signature defined?
The delegate declaration specifies a function signature consisting of a return type and the parameter list. After defining a delegate, you can declare a variable with the type of that delegate. You can then initialize this variable as a reference to any function that has the same signature as that delegate.
Example:
delegate double ProcessDelegate(double param1, double param2);

static double Multiply(double param1, double param2)
{
return param1 * param2;
}

static double Divide(double param1, double param2)
{
return param1 / param2;
}

static void Main (string[ ] args)
{
ProcessDelegate process;
………………
if (input == “M”)
process = new ProcessDelegate(Multiply)
else
process = new ProcessDelegate(Divide
Console.WriteLine(“Result: {0}”, process(param1, param2));
Console.ReadKey();
)

No comments: