Wednesday, March 3, 2010

Setting properties from a dictionary of strings

A code snippet that can be used to set an objects properties via reflection.

See Also:

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);
                }
            }
        }