#1,181 – Instantiating an Object within a Lambda Expression

You can create instance of objects within lambda expression.  You can also optionally return that instance as the result of the expression.

            // Delegate set to dog-creating lambda
            Func<string,Dog> dogCreator = s => {
                Dog d = new Dog(s);
                d.Bark();
                return d;
            };

            Dog d1 = dogCreator("Lassie");

            Thread.Sleep(3000);  // wait 3 secs

            Dog d2 = dogCreator("Kirby");

            // Dump out creation time info
            Console.WriteLine(d1);
            Console.WriteLine(d2);

1181-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,181 – Instantiating an Object within a Lambda Expression

  1. Pingback: Dew Drop – September 12, 2014 (#1854) | Morning Dew

Leave a comment