Information Technology Reference
In-Depth Information
var lambdaAnswer3 = Add( 5 , 12.3 , (a, b) => a + b);
var lambdaLabel = Add( "Here is " , "a label" ,
(a, b) => a + b);
dynamic tomorrow = Add( DateTime .Now, TimeSpan .FromDays( 1 ));
var finalLabel = Add( "something" , 3 ,
(a,b) => a + b.ToString());
Yo u c a n s e e t h a t t h e l a s t m e t h o d r e q u i r e s y o u t o s p e c i f y t h e c o n v e r s i o n
from int to string. It also has a slightly ugly feel in that all those lambdas
look like they could be turned into a common method. Unfortunately,
that's just how this solution works. You have to supply the lambda at a
location where the types can be inferred. That means a fair amount of code
that looks the same to humans must be repeated because the code isn't
the same to the compiler. Of course, defining the Add method to imple-
ment Add seems silly. In practice, you'd use this technique for methods
that used the lambda but weren't simply executing it. It's the technique
used in the .NET library Enumerable.Aggregate(). Aggregate() enumer-
ates an entire sequence and produces a single result by adding (or per-
forming some other operation):
var accumulatedTotal = Enumerable .Aggregate(sequence,
(a, b) => a + b);
It still feels like you are repeating code. One way to avoid this repeated
code is to use Expression Trees. It's another way to build code at runtime.
The System.Linq.Expression class and its derived classes provide APIs for
you to build expression trees. Once you've built the expression tree, you
convert it to a lambda expression and compile the resulting lambda expres-
sion into a delegate. For example, this code builds and executes Add on
three values of the same type:
// Naive Implementation. Read on for a better version
public static T AddExpression<T>(T left, T right)
{
ParameterExpression leftOperand = Expression .Parameter(
typeof (T), "left" );
ParameterExpression rightOperand = Expression .Parameter(
typeof (T), "right" );
BinaryExpression body = Expression .Add(
leftOperand, rightOperand);
Expression < Func <T, T, T>> adder =
Expression .Lambda< Func <T, T, T>>(
 
Search WWH ::




Custom Search