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);

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

One Response to Passing Methods As Parameters in .NET/C#

  1. Mehmet says:

    http://www.swimobile.comFree Mobile Services and Free SMS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s