adamwtiko
adamwtiko

Reputation: 2905

Method passed in as parameter to a Method C#2.0

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

Answers (6)

Jamiec
Jamiec

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

Arseny
Arseny

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

theburningmonk
theburningmonk

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

Nenad Dobrilovic
Nenad Dobrilovic

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

James Curran
James Curran

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

Related Questions