Cover by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

ANALYZING EXPRESSIONS

One of the main driving factors behind the idea of treating code as data is that it enables you to analyze the code at runtime. This is sometimes motivated by the need to understand what the code does — for instance, for logging or debugging purposes — but it also enables you to translate code at runtime into an execution format that is best suited for the task at hand.

The sample project for this chapter contains a class called ExpressionDumper, which walks through an expression tree hierarchically and outputs information about all the elements to the console or some other stream. For the addExpr expression, a call to ExpressionDumper.Output() renders the following hierarchy:

LambdaExpression (

  Parameters:

    ParameterExpression (x)

    ParameterExpression (y)

  Body:

    BinaryExpression:Add (

      Left:

        ParameterExpression (x)

      Right:

        ParameterExpression (y)

    )

)

This is one of the easiest ways to familiarize yourself with the structures used by expression trees: make use of the C# compiler’s capability to generate the trees from code, output them using ExpressionDumper and see how certain constructs are represented.

The following code shows one of the core methods (just the first 20 lines for brevity) in the ExpressionDumper class:

image

private static void Output(Expression expression, TextWriter textWriter,

  int indent) {

  switch ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required