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?
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
}
}
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