Tested with Microsoft Visual C# 2005 Beta 1, .Net 2.0.40607.42
You no longer have to provide a method when instantiating a delegate - you can now provide
code blocks instead. This reduces the overhead involved in having to create defined
methods for handling method calls through delegate instances.
Anonymous Method Delegate Syntax:
Syntax:
DelegateName DelegateVariable = delegate [(method signature)] { [code to execute;] };
Example,
// Define delegate:
public delegate void MyDelegate(String Message);
// Instantiate anonymous method delegate:
MyDelegate myDelegate = delegate(String str) { MessageBox.Show(str); };
// Call delegate anonymous method:
myDelegate("Hello World!");
Example of using both methods to instantiate a delegate:
namespace WhatsNew20AnonymousMethods
{
class Program
{
delegate void MyDelegate(String Message);
static void Main(string[] args)
{
// instantiate a delegate using an ananymous method:
MyDelegate del = delegate (String msg)
{
Console.WriteLine(msg);
};
// execute the anonymous method (code):
del("Hello World!");
// instantiate a delegate using a defined method:
del = new MyDelegate(Program.MyDelegateTarget);
// execute the defined method:
del("Hello World!");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private static void MyDelegateTarget(String Message)
{
Console.WriteLine(Message);
}
}
}