Posted by: Cirilo Meggiolaro | 02/1/2009

Tip of the day #110 – Action delegate

I wrote about delegates and some other features related to delegates on Tip #16, Tip #24, Tip#25 and Tip #41. Now, it is time to check the Action delegate object available under the System namespace.

In very basic steps, to use regular delegates you have to declare the delegate signature, create an instance passing a method that matches the same signature and then invoke it.

The idea of the Action delegate is to encapsulate the delegate signature so you don’t need to declare it explicitly. The limitation is that only parameterless delegates that do not return values may be used. Tomorrow’s tip explores a workaround for this scenario.

How to…

Assuming you have a parameterless method named M that does not return a value:

private void M()
{
    Console.WriteLine(“M method invoked via Action delegate.”);
}

You have to create an Action delegate object and assign M to it:

Action myDelegate = M;

When you want to invoke it you just need to call the delegate like the following code snippet:

myDelegate();

Anonymous methods and lambda expressions

You may use anonymous methods or lambda expressions in conjunction with the Action delegate object to achieve the same results:

Action myDelegate = delegate() { Console.WriteLine(“Using anonymous method with Action delegate.”); };

Action myDelegate = () => Console.WriteLine(“Using lambda expressions with Action delegate.”);

Check Tip #24 for an explanation about anonymous method and Tip#25 for lambda expressions.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: