Search code examples
.net.net-3.5propertiesexpressionexpression-trees

How create an indexed property acess expression in .net 3.5?


In .NET 4.0 one can write something like this:

ParameterExpression objExpr = Expression.Parameter(typeof(SomeIndexedType), "Obj");
ParameterExpression indexExpr = Expression.Parameter(typeof(int), "Index");
Expression indexAccessExpr = Expression.ArrayAccess(objExpr, indexExpr);

Is there a way to create indexed property expression in .NET 3.5?


Solution

  • The index property on a type is flagged with the DefaultMemberAttribute attribute. This property is set against the class/struct/interface. In C# when you define an indexed property (eg public char this[int index]) it'll be given the name Item, although I don't think this is a hard rule.

    Now, the interesting things with properties is that you can call them with parameters (even the getters), so once you've got the name of the index property you just do an Expression.Property. Eg:

    string defaultMember=GetDefaultPropertyName(typeof(SomeIndexType));
    ParameterExpression indexExpr = Expression.Parameter(typeof(int), "Index");
    Expression indexAccessExpr = Expression.Property(objExpr, defaultMember, indexExpr);
    

    Obviously you'll have to implement GetDefaultPropertyName to get the property off the type. Once you've got the attribute the MemberName property tells you which property you'll need to access.