0

I am having dictionary which store Funct. While storing Func ( testDir.Add(1, p => p.Id) )its fine. When i get the Func from dictionary i want the name of property (Id) which i am stored in Func. I had tried Retrieving Property name from lambda expression Get property name and type using lambda expression this links. It works in simple Func. But with dictionary i am getting member = null in GetMemberInfo.

 public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
    {
        var member = expression.Body as MemberExpression;
        if (member != null)
            return member.Member;

        throw new ArgumentException("Expression is not a member access", "expression");
    }


static void Main(string[] args)
        {
            Dictionary<int, Func<Soure.Employee, int>> testDir = new Dictionary<int, Func<Soure.Employee, int>>();
            testDir.Add(1, p => p.Id);
            var testDirValue = testDir[1];
            Expression<Func<Soure.Employee, int>> expr1 = mc => testDirValue(mc);
            MemberInfo member = Program.GetMemberInfo(expr1);
            Console.WriteLine(member.Name);
        }
Community
  • 1
  • 1
Hemant Malpote
  • 891
  • 13
  • 28

1 Answers1

1

The expression you have in expr1 does not actually hold the expression tree for p => p.Id. It holds the expression tree for the lambda mc => testDirValue(mc), which is an expression consisting of a call to an opaque delegate. There is no way to derive information about which property was accessed from this second lambda.

The information you want is encoded into the lambda literal syntax. Once it is stored and retrieved as an arbitrary delegate, this information is no longer available. What you actually want to do is store Expression<Func<Soure.Employee, int>> in your dictionary, so that an expression tree is built from the lambda you add to your dictionary:

var testDir = new Dictionary<int, Expression<Func<Soure.Employee, int>>>();
testDir.Add(1, p => p.Id);
MemberInfo member = GetMemberInfo(testDir[1]);
Console.WriteLine(member.Name); // Id
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139