C# Actions part 2: Lazy evaluation

14 Jul

Lazy Evaluation example:

In a previous post I talked about C# Actions and how they are a useful feature that could provide new shorthand for lazy evaluation. I have since found an excellent article [1] which demonstrates lazy evaluation with LINQ. The advantages in that article show how LINQ queries can minimize memory usage by evaluating upon enumeration rather than just allocating memory for everything the query would return.

Func

Actions are delegates that have a void return type. This makes sense if you are using Actions as event handlers, but for other use cases you will want a return type. In these cases you will want to use Func. One issue I have seen with Func is when you want don’t know how many parameters your function is going to take. If the number is variable then you must implement up to the amount of parameters you want (if overloading). I noticed a few examples of that in the Ninject 1.x source code. To generalize Func and Actions you can use the ‘Delegate’ type (note: the captialization).

A real world use case

A reason for lazy evaluation could be that you want to perform a group of service calls at one time. The service calls could be a transaction style interaction which would want to be disposed afterwards and some of the service calls could be surplus to requirement. If I had a user interface which required a list of products to be loaded, then that screen may not need that data reloaded if it is moving from a screen which has that data loaded. That service call could be pre-evaluated (ie lazy evaluation) to check to see if it is necessary.

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

%d bloggers like this: