13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

240 CHAPTER 9 Lambda expressions and expression treesRunn<strong>in</strong>g list<strong>in</strong>g 9.6 will produce the output“(2 + 3),” which demonstrates thatthe various expression classes overrideToStr<strong>in</strong>g to produce human-readableoutput. Figure 9.1 depicts the tree generatedby the code.It’s worth not<strong>in</strong>g that the “leaf” expressionsare created first <strong>in</strong> the code: youbuild expressions from the bottom up.This is enforced by the fact that expressionsare immutable—once you’ve createdan expression, it will never change,so you can cache and reuse expressionsat will.Now that we’ve built up an expressiontree, let’s try to actually execute it.LeftfirstArgConstantExpressionNodeType=ConstantType=System.Int32Value=2addB<strong>in</strong>aryExpressionNodeType=AddType=System.Int32RightsecondArgConstantExpressionNodeType=ConstantType=System.Int32Value=3Figure 9.1 Graphical representation of theexpression tree created by list<strong>in</strong>g 9.69.3.2 Compil<strong>in</strong>g expression trees <strong>in</strong>to delegatesOne of the types derived from Expression is LambdaExpression. The generic classExpression then derives from LambdaExpression. It’s all slightly confus<strong>in</strong>g—figure9.2 shows the type hierarchy to make th<strong>in</strong>gs clearer.The difference between Expression and Expression is that thegeneric class is statically typed to <strong>in</strong>dicate what k<strong>in</strong>d of expression it is, <strong>in</strong> terms ofreturn type and parameters. Fairly obviously, this is expressed by the TDelegate typeparameter, which must be a delegate type. For <strong>in</strong>stance, our simple addition expressionis one that takes no parameters and returns an <strong>in</strong>teger—this is matched by thesignature of Func, so we could use an Expression to represent theexpression <strong>in</strong> a statically typed manner. We do this us<strong>in</strong>g the Expression.Lambdamethod. This has a number of overloads—our examples use the generic method,which uses a type parameter to <strong>in</strong>dicate the type of delegate we want to represent. SeeMSDN for alternatives.ExpressionLambdaExpressionB<strong>in</strong>aryExpression(Other types)ExpressionFigure 9.2Type hierarchy from Expression up to ExpressionLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!