Erfan Ahmadi
Erfan Ahmadi

Reputation: 31

Passing an Action with Different Parameters

I have a class in C# named Button and I want the Button have a functionality that can be passed through its constructor and whenever the Button was pressed the Action executes.

Button(Rect rect, string text, Action Func);

I have used Action and It worked perfectly until I found out that I can't pass a void Action with arguments.

For example:

void DoSomething(string str);

How can I be able to pass any void Action with any arguments?

Upvotes: 0

Views: 1107

Answers (3)

Backs
Backs

Reputation: 24913

I advice you to use simplefied command pattern: Create base class or interface Command

interface ICommand
{
    void Execute();
}

//Create secific command and pass parameters in constructor:
class Command : ICommand
{
    public Command(string str)
    {
        //do smth
    }
    void Execute()
    {
        //do smth
    }
}

Button(Rect rect, string text, ICommand cmd)
{
    cmd.Execute();
}

Upvotes: 0

Ric
Ric

Reputation: 13248

Sure you can pass arguments, just use the following:

Button b = new Button(.., .., () => DoSomething("YourString");

Upvotes: 0

Luaan
Luaan

Reputation: 63772

The button doesn't have to care about the argument, but it still needs to be passed a delegate with no arguments and returning void. This is easily done:

new Button(rect, text, () => YourMethod(whateverArgument))

Depending on what you're trying to do, whateverArgument can be a local, a constant or a field. Just think about when it's supposed to read the value to pass to the inner method.

Upvotes: 1

Related Questions