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
Here is a version of @DanielMöller's answer updated for modern syntax, with specified exception messages, and documentation.
///
/// 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."
private PropertyInfo GetPropertyInfo(Expression> property)
{
if (property == null) {
throw new ArgumentNullException(nameof(property));
}
if (property.Body is UnaryExpression unaryExp) {
if (unaryExp.Operand is MemberExpression memberExp) {
return (PropertyInfo)memberExp.Member;
}
}
else if (property.Body is MemberExpression memberExp) {
return (PropertyInfo)memberExp.Member;
}
throw new ArgumentException($"The expression doesn't indicate a valid property. [ {property} ]");
}