2

In C# Given a hash table like {id:'1', name:'foo'}

How can I dynamically create an instance of a class that has the same members?

public class product {
    public int id;
    public string name;
}

I know I'm going to run into problems casting but I will deal with those later. Right now I can't even access the members of the class based on the key of the hashtable. Am I going about this the right way?

This is the way I'm currently going about it.

product p = new product();
Type description = typeof(product);
foreach (DictionaryEntry d in productHash)
{
    MemberInfo[] info = description.GetMember((string)d.Key);
    //how do  I access the member of p based on the memberInfo I have?
    //p.<?> = d.Value;
}

Thanks

Tavis
  • 97
  • 1
  • 1
  • 9
  • 1
    Sorry, answered here http://stackoverflow.com/questions/721441/c-how-to-iterate-through-classes-fields-and-set-properties My bad – Tavis Nov 29 '10 at 19:17
  • Glad that answered your question. I had thought you wanted to create the Product class dynamically not just fill it. Reflection is the way to go. – kenny Nov 29 '10 at 19:24

1 Answers1

2

First, you need to access the member as a property. Then, you can ask the property for the value of a particular instance:

PropertyInfo property = description.GetProperty((string) d.Key);

object value = property.GetValue(p, null);

The second parameter is the index, which would take effect only if the property is an indexer.

Bryan Watts
  • 44,911
  • 16
  • 83
  • 88