Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a method as a parameter [duplicate]

Tags:

c#

.net-3.5

I want to be able to pass a method as a parameter.

eg..

//really dodgy code
public void PassMeAMethod(string text, Method method)
{
  DoSomething(text);
  // call the method
  //method1();
  Foo();
}

public void methodA()
{
  //Do stuff
}


public void methodB()
{
  //Do stuff
}

public void Test()
{
  PassMeAMethod("calling methodA", methodA)
  PassMeAMethod("calling methodB", methodB)
}

How can I do this?

like image 285
raklos Avatar asked Oct 25 '10 14:10

raklos


People also ask

Can I pass a method as a parameter?

There's no concept of a passing method as a parameter in Java from scratch. However, we can achieve this by using the lambda function and method reference in Java 8.

Can we pass method as parameter in C#?

In C#, we can also pass a method as a parameter to a different method using a delegate. We use the delegate keyword to define a delegate. Here, Name is the name of the delegate and it is taking parameter. Suppose we have a delegate having int as the parameter.

How do you call a method with parameters in another method in C#?

You can use the Action delegate type. Then you can use it like this: void MyAction() { } ErrorDBConcurrency(e, MyAction); If you do need parameters you can use a lambda expression.

Can you pass a method to another method?

We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method.


2 Answers

You need to use a delegate, which is a special class that represents a method. You can either define your own delegate or use one of the built in ones, but the signature of the delegate must match the method you want to pass.

Defining your own:

public delegate int MyDelegate(Object a);

This example matches a method that returns an integer and takes an object reference as a parameter.

In your example, both methodA and methodB take no parameters have return void, so we can use the built in Action delegate class.

Here is your example modified:

public void PassMeAMethod(string text, Action method)
{
  DoSomething(text);
  // call the method
  method();    
}

public void methodA()
{
//Do stuff
}


public void methodB()
{
//Do stuff
}

public void Test()
{
//Explicit
PassMeAMethod("calling methodA", new Action(methodA));
//Implicit
PassMeAMethod("calling methodB", methodB);

}

As you can see, you can either use the delegate type explicitly or implicitly, whichever suits you.

like image 123
Steve Whitfield Avatar answered Oct 13 '22 01:10

Steve Whitfield


Use Action<T>

Example:

public void CallThis(Action x)
{
    x();
}

CallThis(() => { /* code */ });
like image 33
BrunoLM Avatar answered Oct 13 '22 03:10

BrunoLM