About
In this code snippet, we’ll take a look at anonymous methods in C#.
Anonymous methods don’t have names(obviously). They can be defined with the delegate keyword or by using the lambda expression. They can then be put into a variable of type delegate.
Here is how to implement an anonymous method.
Code:
using System; using System.Collections.Generic; using System.Linq; namespace AnonymousMethod { class Program { static void Main(string[] args) { //Examples of anonymous methods using delegate. Func<string> method = delegate() { return "Hello."; }; Console.WriteLine(method()); Console.WriteLine(""); //Examples of anonymous methods using the lambda expression. Func<int, int, int> add = (a, b) => a + b; Func<int, int> sub10 = a => { return a - 10; }; Console.WriteLine(add(10, 15)); Console.WriteLine(sub10(15)); Console.WriteLine(""); //Example of a anonymous metod List<int> numbers = new List<int>() { 1, 5, 8, 9 }; var query = numbers.Where(n => n > 2); foreach (var item in query) { Console.WriteLine(item); } Console.ReadLine(); } } }