August 2007 - Posts

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.

Posted by PSteele | 2 comment(s)

The next Day of .NET

It's scheduled!  October 20th has been picked for the next Day of .NET.  Here's the scoop:

Day of .NET in Ann Arbor is a one-day conference on all things .NET organized by developers for developers. This event is being offered at no cost to anyone interested in .NET development, and will take place on October 20, 2007 at Washtenaw Community College in Ann Arbor, MI.

If you're interested in speaking at this event, go to the website and submit your abstract.  I've volunteered to be venue coordinator for this event.  Hopefully I don't screw anything up!  That, along with being on the INETA Marketing Committee, is keeping my pretty busy these days so I don't think I'll be speaking at Day of .NET this time.

Day of .Net October 20, 2007 - See You there!

Posted by PSteele | with no comments
More Posts