Decode Member Access Expression : Expression « LINQ « C# / C Sharp






Decode Member Access Expression

        

using System;
using System.Linq.Expressions;
using System.Reflection;

public class TypeUtils
{
    public static MemberInfo DecodeMemberAccessExpression<TEntity, TResult>(Expression<Func<TEntity, TResult>> expression)
    {
        if (expression.Body.NodeType != ExpressionType.MemberAccess)
        {
            if ((expression.Body.NodeType == ExpressionType.Convert) && (expression.Body.Type == typeof(object)))
            {
                return ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member;
            }
            throw new InvalidOperationException(
                string.Format("Invalid expression type: Expected ExpressionType.MemberAccess, Found {0}", expression.Body.NodeType));
        }
        return ((MemberExpression)expression.Body).Member;
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Linq Reflection
2.Get Member Name