Expression vs. delegates

Using LINQ lambda expressions is fun. But did you know that lambdas can be viewed either as delegates or as expression trees? Specifically, both lines from the following snippet compile successfully:

Func<double, string> f = v => v.ToString();
Expression<Func<double, string>> fe = v => v.ToString();

Similarly with Action instead of Func:

Action<double> a = v => Console.WriteLine(v);
Expression<Action<double>> ae = v => Console.WriteLine(v);

The difference only lays in the way the lambda expression is stored: as a delegate or as a tree of objects representing the expression that can eventually be “compiled” to a delegate, if needed, by using Expression.Compile() method, that eventually returns a Func or Action delegate and using that would be just like if you never used Expression type at all.

But when would you ever need Expression type then? The answer is: when you don’t want to call Compile method, of course! And when would you want that? When you would want to convert the expression tree into some other type of expressions or calls, such as how LINQ to SQL or to Entities do: they read the expression tree and generate SQL code to be actually run against an external system! Whenever you need to implement something of that type, you’d thank Microsoft for introducing the generic Expression type.

Advertisements

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in .NET, C# and tagged , , , , . Bookmark the permalink.

Add a reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s