The following code compiles and runs fine.
void myInvokedMethod(string s)
{
Console.WriteLine(s);
}
void myInvoker()
{
Invoke(new MethodInvoker(delegate() { myInvokedMethod("one"); }));
Invoke(new MethodInvoker(delegate { myInvokedMethod("two"); }));
}
When I call myInvoker, both calls to myInvokedMethod get through. What do the parentheses after delegate mean, and why do they appear to be optional?
The parentheses is called the anonymous method parameter list, and is empty in this case. The anonymous method doesn’t have a type – the compiler tries to perform an implicit conversion. If the signature of the anonymous method is given it must match the signature of the delegate.
Implicit conversion is also possible if the following all hold:
This is the case in your second example. So there is no difference between those two lines – both do the same thing. Here is another example:
The last two examples show that
delegate(){}anddelegate{}are not equivalent in general. They are only equivalent in your case becauseMethodInvokertakes no parameters. See the C# specification section 21 for more details and more examples.