Skip to content

Instantly share code, notes, and snippets.

@brianwigfield
Last active December 20, 2015 09:28
Show Gist options
  • Save brianwigfield/6107572 to your computer and use it in GitHub Desktop.
Save brianwigfield/6107572 to your computer and use it in GitHub Desktop.
Expression property extension that works even with implicit castings
public T MakeNewTest<T>(Expression<Func<T, string>> details) where T : class, new()
{
var obj = new T();
details.UnwrapPropertyExpression().SetValue(obj, "initial", null);
return obj;
}
public void Main()
{
var it = MakeNewTest<Test>(_ => _.MyValue);
}
public class Test
{
public string MyValue { get; set; }
}
public static PropertyInfo UnwrapPropertyExpression<T, TO>(this Expression<Func<T, TO>> expression)
{
if (expression.Body is MemberExpression)
return (PropertyInfo)((MemberExpression)expression.Body).Member;
return ((PropertyInfo)((MemberExpression)UnwrapUnary(expression.Body)).Member);
}
static Expression UnwrapUnary(Expression unary)
{
var expression = ((UnaryExpression)unary).Operand;
if (expression is UnaryExpression)
expression = UnwrapUnary(expression);
return expression;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment