Tuesday, March 08, 2005

Passing Methods As Parameters in .NET/C#

Passing Methods As Parameters: Delegates to the Answer
On the ASPAdvice C# list someone had asked, "Is it was possible to pass a method as a parameter."
The answer of course is yes, by using delegates. The follow is a rather simple example.//First, define a delegate with the signature you wish
//to pass as a parameter
public delegate int ComputeTwoNumbers(int x, int y);
//Simple class with 4 methods which match our delegate signature
public class ComplexMathmatics
{
public int Multiply(int x, int y)
{
return x * y;
}
public int Divide(int x, int y)
{
return x/y;
}
public int Subtract(int x, int y)
{
return x - y;
}
public int Add(int x, int y)
{
return x + y;
}
}
//Our example class which takes a method (via our delegate) as a parameter.
public class Calculator
{
public int Compute(int x, int y, ComputeTwoNumbers c2n)
{
return c2n(x,y);
}
}
//Our example in action
//Delcare a new instance of our super complex math class :)
public ComplexMathmatics math = new ComplexMathmatics();
//create our "method" parameters
ComputeTwoNumbers multiply = new ComputeTwoNumbers (math.Multiply);
ComputeTwoNumbers divide = new ComputeTwoNumbers (math.Divide);
ComputeTwoNumbers subtract = new ComputeTwoNumbers (math.Subtract);
ComputeTwoNumbers add = new ComputeTwoNumbers (math.Add);
//lets get ready to work it :)
Calculator calc = new Calculator ();
int x = 4;
int y = 10;
int m = calc.Compute(x,y,multiply);
int d = calc.Compute(x,y,divide);
int s = calc.Compute(x,y,subtract);
int a = calc.Compute(x,y,add);

0 Comments:

Post a Comment

<< Home