The book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress has an explanation of delegates that leads into a study of anonymous methods on page 363. Delegates and anonymous methods lead into a discussion of lambda expressions. Why? Lambda expressions are really just anonymous methods, that were introduced in C# 3.
The book says the following: “What if, however, the method is used only one time—to instantiate the delegate? In that case, other than the syntactic requirement for creating the delegate, there is no real need for a separate, named method. Anonymous methods allow you to dispense with the separate, named method. An anonymous method is a method that is declared inline, at the point of instantiating a delegate.”
What does this mean? First, have a look at the small code sample below. Note that I created a method right in the Program class. It is a static method called Add20(). I qualified it by putting Program. before Add20() only for illustration, because that was not necessary. Below is my code that was inspired by the above mentioned book.
using System; namespace AnonymousMethod { class Program { public static int Add20(int x ) { return x + 20; } static void Main(string[] args) { Console.WriteLine(Program.Add20(1)); } } // OUTPUT: // 21 }
Here below we are adding a little more to the code above. Here we are using a named delegate. In the code that follows, we use an anonymous method.
using System; namespace AnonymousMethod { class Program { // NAMED METHOD public static int Add20(int x ) { return x + 20; } delegate int OtherDel(int InParameter); static void Main(string[] args) { Console.WriteLine(Program.Add20(1)); OtherDel del = Add20; Console.WriteLine(del(5)); Console.WriteLine(del(6)); } } // OUTPUT: // 21 // 25 // 26 }
Below we remove the declaration of the method Add20(). We really don’t need it.
namespace AnonymousMethod2 { class Program { delegate int OtherDel(int InParameter); // define signature static void Main(string[] args) { OtherDel del = delegate (int x) { return x + 20; }; System.Console.WriteLine(del(5)); System.Console.WriteLine(del(6)); } } }
Here is some examples of lambda expressions.
using System; namespace AnonymousMethod2 { class Program { delegate int MyDel(int InParameter); // define sig static void Main(string[] args) { MyDel del = delegate (int x) { return x + 20; }; System.Console.WriteLine(del(5)); System.Console.WriteLine(del(6)); MyDel del2 = (x => x + 20); System.Console.WriteLine(del2(100)); MyDel le1 = (int x) => { return x + 1; }; // Lambda expression MyDel le2 = (x) => { return x + 1; }; MyDel le3 = x => { return x + 1; }; MyDel le4 = x => x + 1; Console.WriteLine($"{ le1(12) }"); Console.WriteLine($"{ le2(12) }"); Console.WriteLine($"{ le3(12) }"); Console.WriteLine($"{ le4(12) }"); } } }