C# - setting a property by reflection with a string value
Posted
by David Hodgson
on Stack Overflow
See other posts from Stack Overflow
or by David Hodgson
Published on 2009-07-06T20:43:19Z
Indexed on
2010/03/08
2:12 UTC
Read the original article
Hit count: 479
Hi, I'd like to set a property of an object through reflection, with a value of type string. So, for instance, suppose I have a Ship class, with a property of Latitude, which is a double.
Here's what I'd like to do:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);
As is, this throws an Argument exception (Object of type 'System.String' cannot be converted to type 'System.Double').
How can I convert value to the proper type, based on propertyInfo?
© Stack Overflow or respective owner