Reputation: 2905
If I have a piece of code such as this:
private void DoOperations(//method passed in)
{
executeA();
executeB();
// run method passed in to DoOpertions()
executeC();
}
Is it possible to pass in a method as a paramter? The method may have X number of parameters itself?
Thanks
Upvotes: 0
Views: 135
Reputation: 136074
Sure it is, for no parameters you want Action
[1]
private void DoOperations(Action action)
{
action();
}
//usage
DoAction( new Action(SayHello) );
private void SayHello()
{
Console.WriteLine("Hello World")
}
[1] http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
Upvotes: 0
Reputation: 7351
yes you can define delegate and DoOperatios() function with argument of that type. enter code here
delegate void AsFunction(string str, string str);// as many arguments as you want
public DoOperations(AsFunction asFunction)
{
asFunction("hello1", "hello2");
}
Upvotes: 0
Reputation: 16051
Just to add to Nenad's answer, there are a number of built-in delegates in the .Net framework which you should try to use as much as possible, rather than re-inventing your own delegates that do the same thing.
Use the Action delegate if the delegate doesn't have a return value, otherwise use the Func delegates, each are overloaded with up to 4 input parameters.
Upvotes: 1
Reputation: 1555
You can pass a delegate. Delegate is a method pointer, with the same signature as the method it is referencing.
See more at Delegates.
Upvotes: 4
Reputation: 58522
Yes, use anonymous functions.
Checkout this post C# searching for new Tool for the tool box, how to template this code
Upvotes: 0
Reputation: 103485
delegate void FunctionX(params object[] args);
private void DoOperations(FunctionX executeX)
{
executeA();
executeB();
executeX("any", "number", "of", "params");
executeC();
}
void MyFunction(params object[] p)
{
// do stuff
}
DoOperations(MyFunction);
Upvotes: 2