25

I have a method that is called when an exception occurs:

public void ErrorDBConcurrency(DBConcurrencyException e)
{
    MessageBox.Show("You must refresh the datasource");
}

What i would like to do is pass this function a method so if the user clicks Yes then the method is called e.g.

public void ErrorDBConcurrency(DBConcurrencyException e, something Method)
{
    if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
        Method();
}

The Method may or may not have parameters, if this is the case i would like to pass them too.

How can i acheive this?

Simon
  • 9,197
  • 13
  • 72
  • 115
  • 1
    Does this answer your question? [Pass Method as Parameter using C#](https://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – Davide Cannizzo Aug 23 '20 at 13:13

5 Answers5

47

You can use the Action delegate type.

public void ErrorDBConcurrency(DBConcurrencyException e, Action method)
{
    if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
        method();
}

Then you can use it like this:

void MyAction()
{

}

ErrorDBConcurrency(e, MyAction); 

If you do need parameters you can use a lambda expression.

ErrorDBConcurrency(e, () => MyAction(1, 2, "Test")); 
kdbanman
  • 10,161
  • 10
  • 46
  • 78
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
8

Add an Action as parameter:

public void ErrorDBConcurrency(DBConcurrencyException e, Action errorAction)
{
   if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
       errorAction()
}

and then you can call it like this

ErrorDBConcurrency(ex, () => { do_something(foo); });

or

ErrorDBConcurrency(ex, () => { do_something_else(bar, baz); });
ChrisWue
  • 18,612
  • 4
  • 58
  • 83
4

You need to use a delegate as the parameter type.

If Method returns void, then something is Action, Action<T1>, Action<T1, T2>, etc (where T1...Tn are the parameter types for Method).

If Method returns a value of type TR, then something is Func<TR>, Func<T1, TR>, Func<T1, T2, TR>, etc.

Jon
  • 428,835
  • 81
  • 738
  • 806
2

Look into the Func and Action classes. You can achieve this using the following:

public void ErrorDBConcurrency(DBConcurrencyException e, Action method)
{
    if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
        method()
}

public void Method()
{
    // do stuff
}
//....

Call it using

ErrorDBConcurrency(ex, Method)

Take a look at this article for some details. If you want your method to take a parameter, use Action, Action, etc. If you want it to return a value, use Func etc. There are many overloads of these generic classes.

Martin Doms
  • 8,598
  • 11
  • 43
  • 60
1
public delegate void MethodHandler(); // The type

public void ErrorDBConcurrency(DBConcurrencyException e, MethodHandler Method) // Your error function

ErrorDBConcurrency (e, new MethodHandler(myMethod)); // Passing the method
Fun Mun Pieng
  • 6,751
  • 3
  • 28
  • 30