C# different ways of declaring a delegate

By admin - Last updated: Friday, October 30, 2009 - Save & Share - Leave a Comment

Lambda is quick and sweet.

class DelegateTests
    {
        public void Run()
        {
            // there are many ways to call method Test
            // 1, declare Func<int, string> delegate
            Func<int, string> func1 = MyFunc;
            Test(func1);

            // 2, implicit delegate
            Test(MyFunc);

            // 3, inline delegate
            Test(delegate(int i) { return i.ToString(); });

            // 4, lambda expression
            Test(n => n.ToString());
        }

        public void Test(Func<int, string> func)
        {
            Console.WriteLine(func(123));
        }

        private string MyFunc(int i)
        {
            return i.ToString();
        }
    }




Posted in Code Notes • Tags: Top Of Page

Write a comment


Captcha: 4 × = eight