A delegate is a type of packaging method call. Just like the type, you can pass the delegate instance between methods and call the delegate instance just like the method. An anonymous function is an "inline" statement or expression that can be used wherever the delegate type is required. You can use an anonymous function to initialize the name delegate, or pass the name delegate (instead of the name delegate type) as the method parameter.
Lambda expressions can be bound to the expression directory tree or a delegate.
Example:
Class Test
{
Delegate Void Testdelegate ( String S );
Static Void M ( String S)
{
Console. writeline (s );
}
Static Void Main ( String [] ARGs)
{
// Original delegate syntax required
// Initialization with a named method.
Testdelegate testdela = New Testdelegate (m );
// C #2.0: A delegate can be initialized
// Inline code, called an "anonymous method." This
// Method takes a string as an input parameter.
Testdelegate testdelb = Delegate ( String S) {console. writeline (s );};
// C #3.0. A delegate can be initialized
// A Lambda expression. The Lambda also takes a string
// As an input parameter (X). The type of X is inferred by the compiler.
Testdelegate testdelc = (x) => {console. writeline (x );};
// Invoke the delegates.
Testdela ( " Hello. My name is m and I write lines. " );
Testdelb ( " That's nothing. I'm anonymous and " );
Testdelc ( " I'm a famous author. " );
// Keep Console window open in debug mode.
Console. writeline ( " Press any key to exit. " );
Console. readkey ();
}
}
/* Output:
Hello. My name is m and I write lines.
That's nothing. I'm anonymous and
I'm a famous author.
Press any key to exit.
*/