.NET Tips and Tricks

Blog archive

Integrating Lambda Expressions for Flexible Processing

When you have a method that could do more than one thing, you have two ways to implement the method: Enclose the different processes in If…Then or Select…Case statements, or implement the strategy pattern. With the strategy pattern, you pass to the method not just data but also the processing. As a result, the method’s code loses all those ugly logic statements, making it easier to test and maintain. One way to pass processing to a method—and, probably, the simplest—is to pass a lambda expression.

To create a method that accepts a lambda expression, you define a parameter using the Func data type. When defining a Func, you pass parameters to the Func declaration that specify the input parameters, and return type of the function that the lambda expression defines. A Func data type can accept up to 17 parameters: The last parameter specifies the return type, while the previous parameters specify the input parameters. For instance, this declaration specifies an expression that accepts two parameters (a string and an integer) and returns a Boolean:

Dim MyFunc As Func(Of String, Integer, Boolean)

A method that allows the developer to pass a lambda expression that specifies a test to perform within the method might look like this:

 Public Function MyTestMethod(ProcLambda _
As Func(Of String, Integer, Boolean)) As Boolean

End Function

A lambda expression that fits this declaration might test the string to see if it's longer than a specified length. Calling MyMethod with that expression would look like this:

 res = MyTestMethod(Function(st, len) st.Length > len)

Within the method, to process the lambda expression, you call its Invoke method, passing the necessary parameters, like this:

Return ProcLambda.Invoke("Peter", 4)

Posted by Peter Vogel on 09/06/2011


comments powered by Disqus

Featured

Subscribe on YouTube