Information Technology Reference
In-Depth Information
Syntax of Anonymous Methods
The syntax of an anonymous method expression includes the following components:
The type keyword
delegate
.
The
parameter list
can be omitted if the statement block doesn't use any parameters.
The
statement block
contains the code of the anonymous method.
Parameter
Keyword
list
Statement block
↓
↓
↓
delegate (
Parameters
) {
ImplementationCode
}
Return Type
An anonymous method does not explicitly declare a return type. The behavior of the imple-
mentation code itself, however, must match the delegate's return type, by returning a value of
that type. If the delegate has a return type of
void
, then the anonymous method code cannot
return a value.
For example, in the following code the delegate's return type is
int
. The implementation
code of the anonymous method must therefore return an
int
on all pathways through the code.
Return type of delegate type
↓
delegate int OtherDel(int InParam);
static void Main()
{
OtherDel del = delegate(int x)
{
return x + 20 ; // Returns an int
};
...
}