#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");

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

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 /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

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

Facebook photo

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

w

Connecting to %s

%d bloggers like this: