Showing posts with label conversion. Show all posts
Showing posts with label conversion. Show all posts

Thursday, February 21, 2008

How to Control.Invoke an Anonymous Method?

Why won't Control.Invoke accept a delegate, even though it's looking for a Delegate?


This might seem like some semantic gymnastics... but when trying to compile this:

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


you'll get:

Argument '1': cannot convert from 'anonymous method' to 'System.Delegate'


which would suggest that a delegate is not a Delegate.

It's not exactly so - the problem is actually that the compiler does not know to what particular subtype of System.Delegate to cast/convert the anonymous method (delegate) to - and it can't create an instance of System.Delegate.

To make the code work, you have to explicitly create an instance of a particular type of a parameterless delegate returning void, e.g.:

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



see: Anonymous methods and Control.Invoke

Tuesday, February 12, 2008

Convert an Array of Integers to an Array of Strings

This is just brilliant!


int[] ints = new int[] { 1, 2, 3, 4 };
string[] strings = Array.ConvertAll(ints, Convert.ToString);
see: Kieran Lynam's Blog