A code snippet that can be used to set an objects properties via reflection.
See Also:
- Stack Overflow : how to set nullable type via reflection code ( c#)?
- Code Project: HyperDescriptor: Accelerated dynamic property access
using System.ComponentModel; using System.Collections.Generic; ///... ////// Set Properties on this instance using key value pairs from a dictionary /// /// Dictionary of keys (property names) and values (value to set property to) public void FromTemplateData(Dictionary<string, string> templateData) { PropertyDescriptorCollection propertyDescriptors = TypeDescriptor.GetProperties(this); foreach (string key in templateData.Keys) { //Find the property, ignore case. PropertyDescriptor propertyDescriptor = propertyDescriptors.Find(key, true);//propertyDescriptors[nodeName]; if (propertyDescriptor != null) { propertyDescriptor.SetValue(this, propertyDescriptor.Converter.ConvertFromInvariantString(templateData[key])); } else { throw new ApplicationException("No property matching name: " + key); } } }