-1

I have Delegate a :

    public delegate void doLog( String value , RichTextBox lger ) ;

    public void doLg(String value, RichTextBox lger)
    {
        lger.AppendText(value);
    }

    doLog a = new doLog(doLg);

I use this delegate in my Invoke call:

_textBox.Invoke(a, new Object[] { "aaaa", _textBox });

How to make all this simpler with lambda expression?

Luthfi
  • 478
  • 1
  • 3
  • 16
vico
  • 17,051
  • 45
  • 159
  • 315

3 Answers3

1

simplest one liner I can think is this one

_textBox.Invoke(new Action(() => { doLog("aaaa", _textBox); }));

(it is working because Action is just delegate)

Spixy
  • 303
  • 4
  • 11
0

If it makes it anything better, you could use Action:

Action<string, RichTextBox> a = (value, lger) => { };

_textBox.Invoke(a, new object[] { "aaaa", _textBox });
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • It does sound like you want to use an action delegate but you haven't provided enough info to show exactly what or why your doing this. – Aaron Gibson Nov 01 '18 at 15:17
  • The question is basically: "How to make all this simpler with lambda expression?" This answer uses a lambda expression through an action to achieve the exact same thing. – Patrick Hofman Nov 01 '18 at 15:18
0

combining the above two answers, I think this is the best compromise:

textBox1.Invoke(new Action(() => { /* your code here */ }), new object[] { "a", "b" });

Edit; borrowed heavily from this question

EDIT 2; an example with parameters:

textBox1.Invoke(new Action<string, RichTextBox>((a, b) => {}), new object[] {"a", new RichTextBox() });
  • What does your answer add over the answer from Spixy? – Patrick Hofman Nov 01 '18 at 15:35
  • the second parameter and the reference to another question where the compile error that caused this question in the first place is answered. So basically it is more complete and has some background as well. –  Nov 01 '18 at 15:40
  • It works fine... just ran it in a dummy windows forms project. –  Nov 01 '18 at 15:45
  • no true, if you want parameters you will need to specify them. Added an example. –  Nov 01 '18 at 15:49
  • 1
    In your first code, you provide a parameterless action *and* parameters. That seems wrong/useless to me. – Patrick Hofman Nov 01 '18 at 15:50
  • You could have pointed that out _in the first place_, that would have been helpful. –  Nov 01 '18 at 15:51