5

I may be missing basic knowledge here, but i ll go for it and ask it.

Lets say we have an array of strings:

ItemCode
ItemDescription

and we have a class:

public class InventoryItem
    {
        public string ItemCode { get; set; }
        public string ItemDescription { get; set; }
    }

I want to be able to reference the properties of an InventoryItem dynamically based on the values of the array.

I need to loop through the array and get the value of the property of the class by the current string member of the array.

How can i do it?

e4rthdog
  • 5,103
  • 4
  • 40
  • 89
  • How are ItemCode and ItemDescription declared? Also where is InventoryItem , show the code please. – Ebad Masood Jul 06 '12 at 10:16
  • One option is to use reflection. See [here][1]. [1]: http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – Maarten Jul 06 '12 at 10:17

2 Answers2

11

You use reflection:

foreach (var name in propertyNames)
{
    // Or instance.GetType()
    var property = typeof(InventoryItem).GetProperty(name);
    Console.WriteLine("{0}: {1}", name, property.GetValue(instance, null));
}

See:

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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

Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93