Why don't anonymous types have an indexer property?

406 views Asked by At

Since anonymous types are compiler-generated anyway, why don't they go one step further with an indexer to access the values of its properties similar to ExpandoObject, but make it statically coded.

Some background: I am currently trying to scrape up any last bit of performance I can in a microORM and one thing sticks out to me: reflection on anonymous types.

Parameters are passed in as an object which while not required to be an anonymous type typically is. I have to use reflection to get each member's name and value, because anonymous types are just compiler generated POCOs really.

After working with ExpandoObject and some of the other dynamic structures in C# I find myself missing Expando's explicit IDictionary interface implementation.

2

There are 2 answers

2
James Ralston On

They don't have an indexer because you have the parameter passed in as the base Object reference type. It is not a reasonable assumption that you could use methods defined on an interface that is not defined in the method contract.

0
Michael Brown On

If you look at the definition of ExpandoObject, you'll see it implements IDictionary and IDynamicMetaObjectProvider (the magic piece that lets your code hook into the DLR). Basically it brings the power of Python dictionaries (dictionaries in Python can be accessed via a string-based "indexer" or using a . accessor as if it were attributes (or even functions) defined directly on the object).

Anonymous types aren't dynamic. They are resolved at compile time. You cannot add, or subtract to their definition.

In general, there is no "dictionary" type access to the reflection API although I don't see why you can't implement it. IDictionary is an interface...you could create an IDictionary implementation that takes an object and resolves the indexer requests using reflection on that object.