/// <summary> /// Sets an object's property with the specified value, /// coercing that value to the appropriate type if possible. /// </summary> /// <param name="target">Object containing the property to set.</param> /// <param name="propertyName">Name of the property to set.</param> /// <param name="value">Value to set into the property.</param> public static void SetPropertyValue( object target, string propertyName, object value) { PropertyInfo propertyInfo = target.GetType().GetProperty(propertyName); if (value == null) propertyInfo.SetValue(target, value, null); else { Type pType = Utilities.GetPropertyType(propertyInfo.PropertyType); Type vType = Utilities.GetPropertyType(value.GetType()); if (pType.Equals(vType)) { // types match, just copy value propertyInfo.SetValue(target, value, null); } else { // types don't match, try to coerce if (pType.Equals(typeof(Guid))) propertyInfo.SetValue( target, new Guid(value.ToString()), null); else if (pType.IsEnum && vType.Equals(typeof(string))) propertyInfo.SetValue(target, Enum.Parse(pType, value.ToString()), null); else if (pType.IsEnum && vType.Equals(typeof(decimal))) propertyInfo.SetValue(target, Enum.Parse(pType, value.ToString()), null); else propertyInfo.SetValue( target, Convert.ChangeType(value, pType), null); } } } } }