Any way to avoid explicitly declaring MyMethodDelegate
in a scenario like this?
bool MyMethod(string x)
{
//...
}
BeginInvoke(new MyMethodDelegate(MyMethod), x);
I know about lambdas a-la ()=>MyMethod(x)
, however I want to avoid them sometimes as they break edit-and-continue.
Edit: just BeginInvoke(MyMethod, x)
does not work:
The best overloaded method match for 'System.Windows.Forms.Control.BeginInvoke(System.Delegate, params object[])' has some invalid arguments
Argument 1: cannot convert from 'method group' to 'System.Delegate'
Argument 2: cannot convert from 'string' to 'object[]'
BeginInvoke is defined as follows:
public IAsyncResult BeginInvoke(Delegate method, params object[] args);
It does not specify any specific delegate type, so the compiler cannot detect which delegate type to instantiate from BeginInvoke(MyMethod. x)
You can often use the simplified version
when a delegate is required. the keyword is often.
However if the compiler can't determine which type of delegate to convert the method group to you will have to help out with an explicit conversion
Lambdas can come in handy when you wish to pass a function that you haven't already defined and don't need at other locations in the code. Then Lambdas (and anonymous functions in general) will be very handy since you can then simply define the function at the spot where you need it.
in the case of BeginInvoke you are correct as noted in the comments that you can't you will need to explicitly convert the method group to a delegate either by casting or by assignment
will compile or you can pass in a lambda because that's interpreted as a Func
For framework >= 3.5 you can use predefined delegates Action<> and Func<> (in your case)
Docs for Func http://msdn.microsoft.com/ru-ru/library/bb549151.aspx