Copy: Hashtable to Properties

  • Thread starter Thread starter James Scott
  • Start date Start date
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!
 
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
 
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.
 
Back
Top