Jon Skeet's answer is absolutely correct (does he have any other kind?) and works well if you'd need to dynamically access say 1000 InventoryItem objects. But if you need to dynamically access more objects, say 10 million, reflection starts to be painfully slow. I have a little helper class I made a while ago that can easily access a property about 26 times faster than reflection (at least on my computer) by creating and compiling a dynamic method to access the property. It's nowhere near as fast as accessing it statically, but since you need to access it dynamically that's not even a consideration. Here's how you use it:
var accessor = new DynamicPropertyAccessor(typeof(InventoryItem).GetProperty("ItemCode"));
foreach (var inventoryItem in warehouse13)
{
Console.WriteLine("{0}: {1}", accessor.Name, accessor[inventoryItem]);
}
You can also use it to set a value with: accessor[item] = "newValue"
. And you can have a collection of accessors if you need to access several properties dynamically. The performance gain will be substantial when you create a DynamicPropertyAccessor
once per property and reuse to access many objects (or the same object many times).
I've posted the DynamicPropertyAccessor
class here: https://gist.github.com/3059427