For example, I have a class:
public class Person
{
public int Id;
public string Name, Address;
}
and I want to call a method to update
Even cleaner IMHO (another variant on @DanielMöller's post)
///
/// Gets the corresponding from an .
///
/// The expression that selects the property to get info on.
/// The property info collected from the expression.
/// When is null .
/// The expression doesn't indicate a valid property."
public static PropertyInfo GetPropertyInfo(this Expression> expression)
{
switch (expression?.Body) {
case null:
throw new ArgumentNullException(nameof(expression));
case UnaryExpression unaryExp when unaryExp.Operand is MemberExpression memberExp:
return (PropertyInfo)memberExp.Member;
case MemberExpression memberExp:
return (PropertyInfo)memberExp.Member;
default:
throw new ArgumentException($"The expression doesn't indicate a valid property. [ {expression} ]");
}
}