Saturday, January 19, 2013

What is Anonymous Methods in c#?


Anonymous Methods

Anonymous Methods allows you to define the code block where you create an object of the delegate. We don’t need to create a separate method for the delegate. Anonymous Methods are useful only for small code because Anonymous Methods code is not reusable, no one can directly call it.

Example: With Anonymous Methods


    class MyDelegates
    {
        // Declare a delegate
        delegate void DisplayMessage(string str);

        static void Main(string[] args)
        {
            //DisplayMessage delegate instance create with Anonymous Method.
            DisplayMessage del = delegate(string str)
            {
                Console.WriteLine(str);
            };

            del("Welcome..");          
            Console.ReadLine();
        }
    }

   Output 

    Welcome..


Example: Without Anonymous Methods


    class MyDelegates
    {
        // Declare a delegate
        delegate void DisplayMessage(string str);

        static void Main(string[] args)
        {
            //Create DisplayMessage delegate instance with Message Method.
            DisplayMessage del = new DisplayMessage(Message);
            del.Invoke("Welcome..");
            Console.ReadLine();
        }

        static void Message(string str)
        {
            Console.WriteLine(str);
        }
    }
   

   Output 

   Welcome..

No comments:

Post a Comment