December 1, 2017
anonymous methods
For delegates, it is mandatory to have a method pre-defined to be used with delegate.
Anonymous methods allow us to define method and delegate in same code without requiring a separate method for delegate. Here is an example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { Func<double> anonMethod1 = delegate () { return 4.5; }; Func<string> anonMethod2 = delegate () { return " DEF "; }; Func<string, string> anonMethod3 = delegate (string param) { return param + " ABC "; }; Func<int, double, string, string> anonMethod4 = delegate (int a, double b, string c) { return a.ToString() + " " + b.ToString() + " " + c; }; Console.WriteLine(anonMethod1()); Console.WriteLine(anonMethod2()); Console.WriteLine(anonMethod3("PAK")); Console.WriteLine(anonMethod4(10,20.5,"PQR")); } } }