Posted by: Cirilo Meggiolaro | 02/21/2009

Tip of the day #130 – Expression class

Tip #111 described the Func delegate. Today we are going to check the Expression<Tdelegate> that stores a lambda expression as an expression tree. The main purpose of using the Expression instead of Func is the ability to serialize, inspect the expression content and convert back into an executable code in runtime when necessary.

How to…

The following code shows a regular function delegate in use and an expression representation of the same function that is compiled in runtime into a function delegate:

/// Creates a simple function that evaluates
/// an integer number and returns true if the
/// parameter is even. Otherwise returns false.
Func<int, bool> even = i => i % 2 == 0;

Output: false

/// Creates an expression tree that holds
/// a function delegate.

Expression<Func<int, bool>> exp = i => i % 2 == 0;

/// Compiles the expression tree into executable code.
Func<int, bool> even = exp.Compile();


Output: true


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: