Wednesday, November 4, 2015

Anonymous Methods

A Anonymous method is a code block assigned to some delegate.
This concept is introduced in .Net Framework 2.0, before it only named methods could be used with delegates

Scenarios to use:
  1. When want to use delegate in same method
  2. When code is small
  3. Performance wise anonymous methods are faster than named method

    class Program
    {
        delegate void delAnonymousMethods(int i, int j);
        static void Main(string[] args)
        {
            //anonymous method
            delAnonymousMethods delAM = delegate(int i, int j)
            {
                Console.WriteLine((i + j).ToString());
            };

            delAM(10, 20);
            Console.ReadLine();
        }
    }


Some examples of Anonymous functions


delegate (int x) { return x + 1; }      // Anonymous method expression
delegate { return 1 + 1; }              // Parameter list omitted
x => x + 1                              // Implicitly typed, expression body
x => { return x + 1; }                  // Implicitly typed, statement body
(int x) => x + 1                        // Explicitly typed, expression body
(int x) => { return x + 1; }            // Explicitly typed, statement body
(x, y) => x * y                         // Multiple parameters
() => Console.WriteLine()               // No parameters
async (t1,t2) => await t1 + await t2    // Async



No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...