Obtained from MSDN Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.
You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. For more information about expression trees in LINQ, see How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic).
Expression trees are also used in the dynamic language runtime (DLR) to provide interoperability between dynamic languages and the .NET Framework and to enable compiler writers to emit expression trees instead of Microsoft intermediate language (MSIL). Uses in application Expression trees are useful when we need to access function logic in order to alter or reapply it in some way.
Linq to SQL is a good example:
var recs = (
from rec in LinqDataContext.Table
where rec.SomeField != 10
select rec );
If we didn't have expression trees this statement would have to return all the records, and then apply the C# where logic to each.
With expression trees that where rec.SomeField != 10 can be parsed into SQL:
--SQL statment executed
select *
from [table]
where [table].[SomeField] != 10
Also we can make dynamic predicate builder - an example here (
http://www.albahari.com/nutshell/predicatebuilder.aspx )
Benefits - Expression trees are usually used when we need to have an ability to traverse some code model, for example in order to generate some other code based on this one.
- Expression trees are using widely in LINQ to SQL, Entity Framework, ASP.NET MVC's HTML extensions where the runtime needs to interpret the expression in a different way (LINQ to SQL and EF: to create SQL, MVC: to determine the selected property or field).
- Expression trees allow you to build code dynamically at runtime instead of statically typing it in the IDE and using a compiler
More information:
https://msdn.microsoft.com/en-us/library/bb397951.aspx --
Thanks & Regards,
RNA Team
Amatya, if this helps please login to Mark As Answer. | Alert Moderator