In C #, why are Expression Trees and when do you need to use them?

When will I need Expression Trees ?

And please provide us a sample of the real world, if available.

+4
source share
4 answers

For example, to implement a typical implementation of INotifyPropertyChanged instead of using strings:

public class Sample : TypeSafeNotifyPropertyChanged { private string _text; public string Text { get { return _text; } set { if (_text == value) return; _text = value; OnPropertyChanged(() => Text); } } } public class TypeSafeNotifyPropertyChanged : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged<T>(Expression<Func<T>> propertyExpression) { PropertyChangedHelper.RaisePropertyChanged(this, propertyExpression, PropertyChanged); } } public static class PropertyChangedHelper { public static void RaisePropertyChanged<T>(object sender, Expression<Func<T>> propertyExpression, PropertyChangedEventHandler propertyChangedHandler) { if (propertyChangedHandler == null) return; if (propertyExpression.Body.NodeType != ExpressionType.MemberAccess) return; MemberExpression memberExpr = (MemberExpression)propertyExpression.Body; string propertyName = memberExpr.Member.Name; RaisePropertyChanged(sender, propertyName, propertyChangedHandler); } private static void RaisePropertyChanged(object sender, string property, PropertyChangedEventHandler propertyChangedHandler) { if (propertyChangedHandler != null) propertyChangedHandler(sender, new PropertyChangedEventArgs(property)); } } 
+8
source

You need an expression tree every time you want to tell some function what needs to be done and not done.

The first example is LINQ-to-SQL. You pass an expression tree so that it can translate that expression tree into SQL. It does not execute the expression, it validates it and translates it into SQL.

+7
source

The expression tree β€” a description of some execution β€” is actually a DOM. When you execute an expression tree, it compiles and then executes. LinqToSql example. When you create a query for LinqToSql, you do it on IQueryable. The query result is an expression tree. When you execute a tree, it is "compiled" in SQL instead of .NET and executed in the database.

Edit: Here you have another good example of an expression used to include related objects in an EF request.

+5
source

Recently, I reorganized a complex comparator object and used expression trees. The comparator object was implemented using reflection, and I modified it to instead build an expression tree using reflection, and then compile the expression tree into a delegate. There is little cost to collecting and compiling a delegate, but after compiling it, it is almost 100 times faster than the reflected solution.

+1
source

All Articles