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

2
  • 1
    Sorry, answered here stackoverflow.com/questions/721441/… My bad Commented Nov 29, 2010 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. Commented Nov 29, 2010 at 19:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.