Skip to content

Instantly share code, notes, and snippets.

@leafbird
Last active November 13, 2018 09:41
Show Gist options
  • Save leafbird/6a9031cf8bc121df9bbb7d1a2148530e to your computer and use it in GitHub Desktop.
Save leafbird/6a9031cf8bc121df9bbb7d1a2148530e to your computer and use it in GitHub Desktop.
namespace Utility
{
using System;
using System.Linq.Expressions;
using System.Reflection;
public static class PropertySelector
{
public static PropertyInfo GetPropertyInfo<T>(this T obj, Expression<Func<T, object>> selector)
{
if (selector.NodeType != ExpressionType.Lambda)
{
throw new ArgumentException("Selector must be lambda expression", "selector");
}
var lambda = (LambdaExpression)selector;
var memberExpression = ExtractMemberExpression(lambda.Body);
if (memberExpression == null)
{
throw new ArgumentException("Selector must be member access expression", "selector");
}
if (memberExpression.Member.DeclaringType == null)
{
throw new InvalidOperationException("Property does not have declaring type");
}
return memberExpression.Member.DeclaringType.GetProperty(memberExpression.Member.Name);
}
private static MemberExpression ExtractMemberExpression(Expression expression)
{
if (expression.NodeType == ExpressionType.MemberAccess)
{
return (MemberExpression)expression;
}
if (expression.NodeType == ExpressionType.Convert)
{
var operand = ((UnaryExpression)expression).Operand;
return ExtractMemberExpression(operand);
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment