When I need the Expression Trees ?
And please provide us with a real world sample if available
Thanks in advance
When I need the Expression Trees ?
And please provide us with a real world sample if available
Thanks in advance
For example to implement a typesafe 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));
}
}
You need an expression tree every time you want to tell some function what needs to be done instead of actually doing it.
The prime example is LINQ-to-SQL. You pass an expression tree so that it can translate this expression tree into SQL. It doesn’t execute the expression, it examines it and translates it to SQL.
Expression tree is description of some execution - actually it is DOM. When you execute expression tree it is compiled and after that executed. Example is LinqToSql. When you build query for LinqToSql you are doing it on the IQueryable. Resulting query is expression tree. When you execute the tree it is "compiled" into SQL instead of .NET and executed on database.
Edit: Here you have another nice example of Expression used for including related entities in EF query.
I recently refactored a complex object comparer and used expression trees. The object comparer had been implemented using reflection, and I modified it to instead build an expression tree using reflection, then compile the expression tree into a delegate. There is a bit of expense to build and compile the delegate, but after it is compiled it is almost 100x faster to call than the reflected solution.