4

How do I create expression tree for reading a value by array access for an IDictionary<string,object>?

I want to represent:

((IDictionary<string,object>)T)["KeyName"]

I can't find any example of ArrayAccess being used to access with string name. I want something like:

var parameterExpression = Expression.Parameter(typeof(IDictionary<string, object>));

var paramIndex = Expression.Constant("KeyName");

var arrayAccess = Expression.ArrayAccess(parameterExpression, paramIndex);

I get error stating it is not an array. What is correct way to do this?

Guerrilla
  • 13,375
  • 31
  • 109
  • 210

1 Answers1

6

You probably* want to access the property Item:

var dic = new Dictionary<string, object> {
    {"KeyName", 1}
};
var parameterExpression = Expression.Parameter(typeof (IDictionary<string, object>), "d");
var constant = Expression.Constant("KeyName");
var propertyGetter = Expression.Property(parameterExpression, "Item", constant);

var expr = Expression.Lambda<Func<IDictionary<string, object>, object>>(propertyGetter, parameterExpression).Compile();

Console.WriteLine(expr(dic));

If you pop the hood on a class with an indexer, there is an Item property. Consider this example:

class HasIndexer {
    public object this[int index] {
        get { return null; }
    }
}

has the following (relevant to indexers) IL:

.property instance object Item(
    int32 index
)
{
    .get instance object ConsoleApplication8.HasIndexer::get_Item(int32)
}

.method public hidebysig specialname 
    instance object get_Item (
        int32 index
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 2 (0x2)
    .maxstack 8

    IL_0000: ldnull
    IL_0001: ret
} // end of method HasIndexer::get_Item
Community
  • 1
  • 1
jdphenix
  • 15,022
  • 3
  • 41
  • 74