#1,169 – Lambdas Supersede Anonymous Methods

Lambda expressions were introduced in C# 3.0 and supersede anonymous methods, which were introduced in C# 2.0.  There are some differences between lambda expressions and anonymous methods, but lambdas are now the preferred way to write inline code.

        static void Main(string[] args)
        {
            Dog d = new Dog("Bowser");

            // C# 1.0 - Named method
            d.Barked += d_Barked;

            // C# 2.0 - Anonymous method
            d.Barked += delegate (object sender,string e) {
                Console.WriteLine("My dog says {0}", e); };

            // C# 3.0 - Lambda expression
            d.Barked += (s, e) => Console.WriteLine("My dog says {0}", e); 

            d.Bark();

            Console.ReadLine();
        }

        static void d_Barked(object sender, string e)
        {
            Console.WriteLine("My dog says {0}", e);
        }

1169-001

Advertisements