0

I have the following working code sample:

public void ClearLogText() => this.TxtLog.Invoke((Action)delegate {this.TxtLog.Text = string.Empty;});

How would I properly add parameters?

public void SetControlText(Control control, string text) => this.Invoke((Action<Control, string>delegate (Control x, string y) {x.Text = y;});

The problem that I have is how to use the parameters into the function, in this case control and text.

Note: The method could have been anything. It is the concept that I care about, not what the method does. That was simply the first thing that came to mind.

Visual Studio complains about the obvious, namely that I am not using the arguments into the method.

I already know how to work with Actions, such as illustrated by this answer. What throws me off is the Invoke and delegate parts.

private void NotifyUser(string message, BalloonTip.BalloonType ballType)
{
    Action<string, BalloonTip.BalloonType> act = 
        (m, b) => BalloonTip.ShowBalloon(m, b);

    act(message, ballType);
}

I would also like to keep the answer to one line using the construct this.X.Invoke((Action)delegate..., hence this question, otherwise the answer would be:

    public delegate void DelegateSetControlText(Control control, string text);

    public void SetControlText(Control control, string text)
    {
        if (true == this.InvokeRequired)
        {
            Program.DelegateSetControlText d = new Program.DelegateSetControlText(this.SetControlText);
            this.Invoke(d, new object[] { control, text });
        }
        else
            control.Text = text;
    }
Sarah Weinberger
  • 15,041
  • 25
  • 83
  • 130
  • What about doing `this.Invoke(delegate (Control x, string y) {x.Text = y;}, new object[] {control, text});`? – juharr May 08 '20 at 18:51
  • @juharr tosses `Error CS1660 Cannot convert anonymous method to type 'Delegate' because it is not a delegate type`. I always used to use the long method until a top coder at a company showed me the short version. He mentioned that the `Action` thing was necessary. I loved the simplicity of the statement even readability. I wanted to extend that by adding parameters, just I am missing something obvious. – Sarah Weinberger May 08 '20 at 19:11

1 Answers1

0

There's no need to include the delegate cast in the actual call.
The parameters go into the 2nd argument of the Invoke method, being a params object array, here containing control and text.

public void SetControlText(Control control, string text)
    => this.Invoke((Action<Control, string>)((ctrl, txt) => ctrl.Text = txt), control, text);
pfx
  • 20,323
  • 43
  • 37
  • 57