Anonymous methods and Control.Invoke

I saw an interesting question posted in one of the Microsoft newsgroups today.  I'll paraphrase here:

I can use anonymous methods with something like the Thread class ctor:

Thread t = new Thread(delegate() { Console.WriteLine("new thread"); });

But if I try the same thing with Control.Invoke:

this.Invoke(delegate() { MessageBox.Show("Hello"); });

I get an error: "Argument '1': cannot convert from 'anonymous method' to 'System.Delegate' 

The problem the user is seeing is that the Thread ctor accepts a specific delegate -- the ThreadStart delegate.  The C# compiler will check and make sure your anonymous method matches the signature of the ThreadStart delegate and, if so, produces the proper code under-the-covers to create the ThreadStart delegate for you.

But Control.Invoke is typed as accepting a "Delegate".  This means it can accept any delegate-derived type.  The example above shows an anonymous method that has a void return type and takes no parameters.  It's possible to have a number of delegate-derived types that match that signature (such as MethodInvoker and ThreadStart -- just as an example).  Which specific delegate should the C# compiler use?  There's no way for it to infer the exact delegate type so the compiler complains with an error.

2 Comments

  • You can cast your anonymous delegate to some specific type of delegate (ThreadStart would work here).

    [code]
    this.Invoke(new ThreadStart(delegate() {MessageBox.Show("Hello"); }));
    [/code]

  • More logical would be new MethodInvoker(delegate() { }) blah blah blah

    (Which, in my opinion, would be nice to do under the covers so you don't have the silliness of

    Invoke(new MethodInvoker(delegate() { ; }));

    which is not very maintainable, I think.

    But anyway it's just silly for the compiler to complain that delegate() {} is not a Delegate.

Comments have been disabled for this content.