Setting a property by reflection with a string value
I notice a lot of people are recommending Convert.ChangeType
- This does work for some cases however as soon as you start involving nullable
types you will start receiving InvalidCastExceptions
:
http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx
A wrapper was written a few years ago to handle this but that isn't perfect either.
http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx
As several others have said, you want to use Convert.ChangeType
:
propertyInfo.SetValue(ship,
Convert.ChangeType(value, propertyInfo.PropertyType),
null);
In fact, I recommend you look at the entire Convert
Class.
This class, and many other useful classes are part of the System
Namespace. I find it useful to scan that namespace every year or so to see what features I've missed. Give it a try!
You can use Convert.ChangeType()
- It allows you to use runtime information on any IConvertible
type to change representation formats. Not all conversions are possible, though, and you may need to write special case logic if you want to support conversions from types that are not IConvertible
.
The corresponding code (without exception handling or special case logic) would be:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
I tried the answer from LBushkin and it worked great, but it won't work for null values and nullable fields. So I've changed it to this:
propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
propertyInfo.SetValue(ship, safeValue, null);
}