Copy: Hashtable to Properties

J

James Scott

Hello,

I have a values stored in a Hashtable hash and I want assign them as
properties to an object obj

obj.x1 = (String)hash[x1];
obj.x2 = (long)hash[x2];
obj.x3 = (int)[x3];
.....


Is there a better (more reusable) way, like this Pseudocode:

foreach (DictionaryEntry de in hash) {
obj.(de.key) = (de.Value.GetType())hash[de.Value];
}

Thanks!
 
A

Andy

You'd have to use reflection, something like this:

Type objType;
PropertyInfo property;

objType = obj.GetType();

foreach( DictionaryEntry de in hash ) {
property = objType.GetProperty( de.key );
property.SetValue( obj, hash[ de.key ] );
}

You may have to cast the value out of the Hashtable to match what the
property expects, so you may need to have a switch statement in there
that looks at property.PropertyType.

HTH
Andy
 
A

Adam Clauss

property.SetValue( obj, hash[ de.key ] );
You may have to cast the value out of the Hashtable to match what the
property expects, so you may need to have a switch statement in there
that looks at property.PropertyType.

No casting is required - SetValue would just cast it back to object anyway.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top