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 ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.