Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I need the Expression Trees ?

And please provide us with a real world sample if available

like image 814
Homam Avatar asked Nov 29 '22 18:11

Homam


2 Answers

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));
    }
}
like image 71
Scordo Avatar answered Dec 02 '22 07:12

Scordo


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.

like image 26
Timwi Avatar answered Dec 02 '22 06:12

Timwi