2

I need explanations.. why the following code give an: Parameter count mismatch ?

C# Code:

//... 
public delegate int FindInRichTextBoxMethod(RichTextBox rtx, string target, int index);
 public int FindInRichTextBox(RichTextBox rtx, string target, int index)
    {
        return rtx.Find(target, index, RichTextBoxFinds.None);
    }
// ... 
int start; 
string tempState = "foo";

if (lista.InvokeRequired) {
  object find = Invoke((FindInRichTextBoxMethod)delegate
                            {
                                return FindInRichTextBox(list, tempState, len);
                            });  

                            start = (int)find;
} else {

      start = FindInRichTextBox(list, tempState, len);
 }

Thanks in advance.

svick
  • 236,525
  • 50
  • 385
  • 514
The Mask
  • 17,007
  • 37
  • 111
  • 185

2 Answers2

2

The arguments to Invoke() include a delegate, and the arguments passed to that delegate. You're attempting to pass a FindInRichTextBoxMethod delegate, but that delegate type takes three arguments. You need to:

  1. construct a delegate with your FindInRichTextBox method, and then
  2. pass in the parameters to that delegate.

Something like this:

var finder = new FindInRichTextBoxMethod(FindInRichTextBox);
object find = Invoke(finder, new object[] { list, tempState, len }); 

Another route is to pass in a closure, sort of like you're attempting in your sample. In your case the error is due to the cast to a FindInRichTextBoxMethod, so the Invoke is expecting arguments. Instead, you could ignore the cast and pass in an anonymous delegate like this:

var find = Invoke(delegate { return FindInRichTextBox(list, tempState, len); });

This won't work, though, because the compiler can't determine exactly what you want to do with that anonymous delegate. Similarly, a lambda can't be automatically converted either:

var find = Invoke(() => FindInRichTextBox(list, tempState, len));

To see why and how to fix the problem, read Why must a lambda expression be cast when supplied as a plain Delegate parameter.

Community
  • 1
  • 1
ladenedge
  • 13,197
  • 11
  • 60
  • 117
0

Are you getting this in the Invoke call? I usually pass Invoke a delegate and then an object array containing the variables you want to pass.

Rob Haupt
  • 2,104
  • 1
  • 15
  • 24