#550 – Anonymous Method Does Not Require Formal Parameters

An anonymous method declares the body of code to execute for a delegate inline with the declaration of the delegate instance.

In the example below, the delegate type takes a single string parameter and we include this parameter in our declaration of the anonymous method.

        private delegate void StringHandlerDelegate(string s);

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

The anonymous method expression shown above includes a list of format parameters, in this case a single string parameter. However, this list of parameters is optional, even if the delegate type includes one or more parameters. In the example below, we define a second anonymous method for the same delegate type, but without any formal parameters.

            StringHandlerDelegate del2 =
                delegate { Console.WriteLine("I'm ignoring my string parameter!"); };
            del2("Ignore me");

Advertisement