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
?
I will answer this with a general answer. Usually these answers not working with guids. Here is a working version with guids too.
Are you looking to play around with Reflection or are you looking to build a production piece of software? I would question why you're using reflection to set a property.
I notice a lot of people are recommending
Convert.ChangeType
- This does work for some cases however as soon as you start involvingnullable
types you will start receivingInvalidCastExceptions
:A wrapper was written a few years ago to handle this but that isn't perfect either.
You can use a type converter (no error checking):
In terms of organizing the code, you could create a kind-of mixin that would result in code like this:
This would be achieved with this code:
MPropertyAsStringSettable
can be reused for many different classes.You can also create your own custom type converters to attach to your properties or classes:
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: