When I need the Expression Trees ?
And please provide us with a real world sample if available
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With