Using Anonymous Methods

In the example in Listing 9.1, there is a method defined on the class for each delegate. In other words, when an instance of the delegate is created, the name of the method is passed to the constructor, as shown following:

MessagePrintDelegate mpDel = new MessagePrintDelegate(PrintMessage); 

Here, PrintMessage is the name of a method that has been defined on the class. Depending on your needs and the type of programming you are doing, it could become extremely tedious and inefficient to code a separate method for each delegate instance that you create.

Anonymous methods allow you to essentially define your method "on the fly" at the same time that you are instantiating the delegate. Anonymous methods are also referred to as "inline methods" by other programming languages.

Another advantage of anonymous methods that sets them apart from using fixed method definitions is that the code written inside your anonymous method has access to variables in the same scope as the definition. This is extremely powerful because it eliminates the need to pass unnecessary or redundant data into the fixed method itself (thereby needlessly bloating the delegate's definition) by allowing the anonymous method to access the data directly.

Listing 9.2 illustrates the use of anonymous methods compared with the use of a fixed method.

Listing 9.2. Anonymous Methods Sample

using System; using System.Collections.Generic; using System.Text; namespace AnonMethods { class Program { delegate void MessagePrintDelegate(string msg); static void Main(string[] args) {     // named-delegate invocation     MessagePrintDelegate mpd = new MessagePrintDelegate(PrintMessage);     LongRunningMethod(mpd);     // anonymous method     MessagePrintDelegate mpd2 = delegate(string msg)     {         Console.WriteLine("[Anonymous] {0}", msg);     };     LongRunningMethod(mpd2);     // use of 'outer variable' in anonymous method     string source = "Outer";     MessagePrintDelegate mpd3 = delegate(string msg)     {         Console.WriteLine("[{0}] {1}", source, msg);     };     LongRunningMethod(mpd3);     Console.ReadLine(); } static void LongRunningMethod(MessagePrintDelegate mpd) {     for (int i = 0; i < 99; i++)     {        if (i % 25 == 0)        {            mpd(                string.Format("Progress Made. {0}% complete.", i));        }     } } static void PrintMessage(string msg) {     Console.WriteLine("[PrintMessage] {0}", msg); } } } 

Figure 9.2 shows the output of the anonymous method sample.

Figure 9.2. Output of anonymous method sample.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: