Current .Net Version: 2.0.50727
Home
Articles
C# & .Net Framework Reference
Practice C# Online
XML Web Services
RSS Feeds
Code Snippets
T-SQL Scripts
Videos
Valuable Links
Contact Us
Mike's C#, VS.NET and SQL Blog




ROR XML Info.
What's New in C# 2.0 - Anonymous Methods
Author: Michael G.     Last Updated:9/29/2005 8:03:35 PM
Category(ies): C# 2.0, .Net Framework 2.0
Description: Learn all about the new C# 2.0 Framework feature: Anonymous Methods.
  Add & View Comments About this Article

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); } } }

Comments Click Here to Add your Comment
By ds @ 4/24/2006 5:05:44 AM

Informative article
 
COPYRIGHT/DISCLAIMER | CONTACT US