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 ArgumentException
:
Object of type 'System.String' cannot be converted to type 'System.Double'.
How can I convert value to the proper type, based on propertyInfo
?
As several others have said, you want to use
Convert.ChangeType
: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!If you are writing Metro app, you should use other code:
Note:
instead of
Using
Convert.ChangeType
and getting the type to convert from thePropertyInfo.PropertyType
.You're probably looking for the
Convert.ChangeType
method. For example:You can use
Convert.ChangeType()
- It allows you to use runtime information on anyIConvertible
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 notIConvertible
.The corresponding code (without exception handling or special case logic) would be:
Or you could try: