Having read in article "Anonymous Methods" (as part of the articles series "Delegates and Lambda Expressions in C# 3.0") the phrase:
"Advanced Topic: Parameterless Anonymous Methods
... anonymous methods are allowed to omit the parameter list (
delegate { return Console.ReadLine() != ""}
, for example). This is atypical, but it does allow the same anonymous method to appear in multiple scenarios even though the delegate type may vary"*
I became a little confused.
IMO (can't find now but as far as I remember), the type is determined by parameter list but not by return type of a method. Is it correct?
So, how can the types of a parameterless method or a delegate differ?
Any (simplest possible) code example illustrating the differing parameterless delegate type for the same anonymous method would be appreciated.
The parameter lists are not allowed to differ. But with the anonymous method, it is legal to omit the parameter list entirely. The compiler will know what the parameter list must look like already, so no need to write it. Of course, if you are going to use the parameters (which you are, usually), then you have to specify and name them.
I think this illustrates:
Then the following is legal:
Note, no parenthesis
( ... )
after keyworddelegate
.If, however, you specify the parameters in parenthesis, of course they must match the type:
In all cases, when you invoke the delegate, use the correct parameters:
Lambda expression syntax is a little different in this respect. Her you can never omit the parameters. But you can omit the types of the parameters in many cases. And if there is exactly one parameter, and you omit its type, then you can also omit the parenthesis.