0

I have a function with a parameter and i want to call it as a parameter into another function using Action . this is the code :

    public void msg(string name)
    {
        MessageBox.Show("Hello " + name);
    }

    public void CallMethod(Action<object> Function)
    {

        Function();

    }

it gives me an error when call Method function with msg parameter :

    private void Form1_Load(object sender, EventArgs e)
    {
        CallMethod(msg("John"));
    }

I don't want to send the parameter in Method function like this :

    public void CallMethod(Action<object> Function)
    {

        Function("John");

    }

any help?

3
  • 1
    When you do CallMethod(msg("Jhon")) you are passing the result of calling msg("Jhon") into the CallMethod method. The result of msg("Jhon") is void - i.e. nothing. So it doesn't make sense. Question...why do you want/need to do this? If we understand the overall purpose of trying to create this CallMethod method, then we might be able to suggest a good way to achieve it. At the moment it doesn't seem to do anything useful, because you could just call the same method directly. Commented Nov 20, 2019 at 9:22
  • What is the purpose of CallMethod? You need parameter, if you don't want to hardcode "Jhon", but why not calling msg("Jhon") directly? Commented Nov 20, 2019 at 9:23
  • for example, i want to create a function with Try - Catch for all functions and just pass the function name to it. Commented Nov 20, 2019 at 9:24

1 Answer 1

7

You can create generic method with parameter:

public void CallMethod<T>(Action<T> Function, T parameter)
{
    ...
    Function(parameter);
    ...
}

and use it like this:

CallMethod(msg, "John");

Another possibility is to pass delegate using lambda:

public void CallMethod(Action action)
{
    ...
    action();
    ...
}

the usage:

 CallMethod(() => msg("John"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.