Last active
December 20, 2015 09:28
-
-
Save brianwigfield/6107572 to your computer and use it in GitHub Desktop.
Expression property extension that works even with implicit castings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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