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
Figure 9.2 shows the output of the anonymous method sample.
Figure 9.2. Output of anonymous method sample.