Fun with Anonymous Method and Lambda

There are always multiple ways to write code to perform the same functionaltiy. With Lambda, we have even more options. Let’s say I want to use a delegate to perform different math functions I could do something like this:

    class Program
    {
        public delegate int MyHandler(int param);

        static void Main(string[] args)
        {
            Compute(SquareIt, 5);
            Compute(AddTen, 5);
 

            Console.ReadKey();
        }

        static void Compute(MyHandler handler, int max)
        {
            for (int i = 0; i < max; i++)
                Console.WriteLine(handler(i));
        }

        private static int SquareIt(int input)
        {
            return input * input;
        }

        private static int AddTen(int input)
        {
            return input + 10;
        }
    }

Now I could use an anonymous method to simplified the code a little:

    class Program
    {
        public delegate int MyHandler(int param);

        static void Main(string[] args)
        {
            Compute(SquareIt, 5);
           
            //The next line does exactly as "Compute(AddTen, 5);"
            Compute(new MyHandler(delegate(int x) { return x + 10; }), 5);

            Console.ReadKey();
        }

        static void Compute(MyHandler handler, int max)
        {
            for (int i = 0; i < max; i++)
                Console.WriteLine(handler(i));
        }

        private static int SquareIt(int input)
        {
            return input * input;
        }

    }

Well, I’m still not too happy about having to instantiate a new MyHandler so let’s change line 10 up there to this:


Compute(delegate(int x) { return x + 10; }, 5);

Now that looks much better. Now let’s have some real fun by using Lambda. Line 10 now can look like this:


Compute(x => x + 10, 5);

I guess now it’s pretty obvious how lambda cound help your code more readible and concise.

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s

Follow

Get every new post delivered to your Inbox.