Sunday 22 April 2012

Actions and Funcs (part 3).....Func as Selector

Hello again.
This post is the third in my exploration of the usage of Actions and Funcs in building more expressive syntax for libraries.  So far, the posts in this series are:

1. Actions and Funcs.....Intro
2. Actions and Funcs (part 2).....Actions as Builder

So, another cool simple usage of Funcs when designing an API are as a selector.  Funcs provide a nice way to select one of many options while still providing a smart default.  So lets jump into some code:


The small console program above shows a selection of an enum (Color) for a Brush.  You can see in the ChooseColor method we send in Color.Yellow as the default.  This allows us to select the input parameter itself as the Color with the first selection line brush.ChooseColor(c => c);. In the second selection line brush.ChooseColor(c => Color.Red);, the Color.Red is selected. As expected, this program outputs:

Choose Default: Yellow Color Selected: Red Press <enter> to close.

When seeing code like this for the first time, I was confused. I thought, "What exactly is returning a value?". Then I found out a cool piece of syntactic sugar built into Func<T, T>. Basically, if the implementation of the Func<T, T> is a single line (so what is on the right-hand side of the => operator), the compiler will place a return before the code for you. So after compiling brush.ChooseColor(c => Color.Red); becomes brush.ChooseColor(c => { return Color.Red });. This allows for much cleaner and expressive code for examples like this. By the way, if you want a multi-line Func<T, T> then it will require the curly braces.

Well, that is about all I have this time. I think this is a cool little example of where Func<T, T> can make code expressive in a different way and might provide another option when designing a class that selects a value type like Color. Hope this helps.

No comments:

Post a Comment