#549 – Anonymous Method Basics

Recall that an instance of a delegate is an object that refers to one or more methods.  Code that has access to the delegate  instance can execute the various methods via the delegate.

        private delegate void StringHandlerDelegate(string s);

        static void Main()
        {
            StringHandlerDelegate del1 = Method1;
            del1("Invoked via delegate");
        }

        static void Method1(string text)
        {
            Console.WriteLine(text);
        }

An anonymous method is a shorthand for declaring a delegate instance that allows declaring the code to execute as part of the delegate’s declaration, rather than in a separate method.

The code below is equivalent to the example above, but using an anonymous method, rather than a separately defined method.

        private delegate void StringHandlerDelegate(string s);

        static void Main()
        {
            StringHandlerDelegate del1 =
                delegate (string s) { Console.WriteLine(s); };
            del1("Invoked via delegate");
        }
Advertisements