C# Action’s

5 Jul

When playing around with UI events it is sometimes handy to use lambda notations of actions to do a tidy inline event-action handler definition such as:

Button1.Click += (sender, args) => Debug.WriteLine("Button Click");
 

If we delve a little deeper into Actions, we can use them to pass around code snippets/functions.

Action<String> action = (input) => Debug.WriteLine("Testing" + input); 
 

I have heard many arguments against functional features such as actions in C# however I do feel that they are very useful in edge cases. One such case could be the mass adding of items to a dictionary, such as:

var namesDictionary = new Dictionary<int, string>();
 
namesDictionary.Add(1,"One");
namesDictionary.Add(2,"Two");
namesDictionary.Add(3,"Three");
 

If we wanted to keep our code maintainable we might want to reduce our dependency to the Add method (especially if we had lots of dictionary add statements).

Action<int,string> addAction = (key,value) => namesDictionary.Add(key,value);
//Action<int,string> addAction = namesDictionary.Add; //short syntax

addAction(1, "One");  //etc
 

Note that this dictionary example is a bad example as the collection initialization could be used here which is likely the most optimal solution. The following shows how the collection initialization could have been used:

var namesDictionary = new Dictionary<int, string> {{1, "One"}, {2, "Two"}, {3, "Three"}};
 

This example also could have been solved more optimally using extension method(s), by extending the dictionary, dependency injection, lambda foreach statement, foreach loop etc. With that said, Actions are important in allowing for lazy evaluation/delayed invocation. I am not going to get into lazy evaluation in this post, but I recommend checking out the Haskell language community for lazy evaluation ideas. I highly recommend the following link for understanding how evaluation/manipulation of lambda expressions work.

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Advertisements

One Response to “C# Action’s”

Trackbacks/Pingbacks

  1. C# Actions part 2: Lazy evaluation « Richards blog - July 14, 2009

    […] a previous post I talked about C# Actions and how they are a useful feature that could provide new shorthand for […]

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

%d bloggers like this: