Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value of Expression<Func<T>> inside a function

Here is a part of complete argument validation system I've wrote which validates user's given argument:

public void Validate<T>(Expression<Func<T>> argExpr, bool justClean) where T : IComparable, IComparable<T>, IConvertible, IEquatable<T>
{
    var expressionBody = (MemberExpression)argExpr.Body;
    var argName = expressionBody.Member.Name;
    var value = argExpr.Compile().Invoke();
    if(!justClean)
        //check above value against invalid values and throw exception
    else
        //clean the value and MY QUESTION: set member's value
}

Now we need to set that expression's member value to cleaned version of given value like this:

Validate(() => item.ItemName, true);

As a result I expect item.ItemName has a cleaned value which was set inside Validate method.

Please notice that we can't simply return that value as a function result, because of my code flow. So, is there any way to do this?

like image 258
Mehdi Avatar asked Apr 19 '26 09:04

Mehdi


1 Answers

You can generate a setter expression base on the expression that is sent to the function:

public static void Validate<T>(Expression<Func<T>> argExpr, bool justClean) where T : IComparable, IComparable<T>, IConvertible, IEquatable<T>
{
    var expressionBody = (MemberExpression)argExpr.Body;
    var argName = expressionBody.Member.Name;
    var value = argExpr.Compile().Invoke();
    if (!justClean)
    {
    }
    else
    {
        var param = Expression.Parameter(typeof(T));
        var setter = Expression.Lambda<Action<T>>(
            Expression.Assign(
                expressionBody,
                param
            ),
            param
        ).Compile();
        setter(default(T)); // Used default(T) as an example, can be any other T value 
    }
}
like image 108
Titian Cernicova-Dragomir Avatar answered Apr 21 '26 23:04

Titian Cernicova-Dragomir