Page 44 - MSDN Magazine, September 2019
P. 44

.NET DEVELOPMENT
Expression Trees in Visual
Basic and C#
Zev Spitz
Imagine if you had objects that represented parts of a program. Your code could combine these parts in various ways, creatinganobjectthatrepresentedanewprogram.Youcouldcom- pile this object into a new program and run it; your program could even rewrite its own logic. You could pass this object to a different environment, where the individual parts would be parsed as a set of instructions to be run in this other environment.
Welcome to expression trees. This article aims to provide a high-level overview of expression trees, their use in modeling code operations and runtime code compilation, and how to create and transform them.
A Note About Language For many language features in Visual Basic and C#, the syntax is actually just a thin wrapper over lan- guage-agnostic .NET types and methods. For example, C#’s foreach
loop and Visual Basic’s For Each construct both call into the IEnumerable-implementing type’s GetEnumerator method. LINQ keywordsyntaxisresolvedintomethodssuchasSelectandWhere with the appropriate signature. A call to IDisposable.Dispose wrapped in error handling is generated every time you write Using in Visual Basic or a using block in C#.
This is true of expression trees, as well—both Visual Basic and C# have syntactic support for creating expression trees, and can use the .NET infrastructure (in the System.Linq.Expressions name- space) for working with them. As such, the concepts described here apply equally well to both languages. Whether your primary development language is C# or Visual Basic, I believe you’ll find value in this article.
Expressions, Expression Trees and
the Types in System.Linq.Expressions
An expression in Visual Basic and C# is a piece of code that returns
a value when evaluated, for example:
42 "abcd" True n
Expressions can be composed of other expressions, such as:
x+ y
"abcd".Length < 5 * 2
These form a tree of expressions, or an expression tree. Consider n + 42 = 27 in Visual Basic, or n + 42 == 27 in C#, which can be separated into parts as shown in Figure 1.
This article discusses:
• Mapping code to APIs with expression trees • Constructing expression trees
• Expression tree visitors
• Runtime code compilation
Technologies discussed:
Expression Trees, C#, Visual Basic .NET
Code download available at:
bit.ly/2yku7tx
36 msdn magazine


































































































   42   43   44   45   46