Consider this code:
var future = new Future();
future.GetType().GetProperty(info.Name).SetValue(future, converted);
In the code above we should pass two arguments for SetValue
. First,The object that we want to set its property. Second,the new value. But we select the specific property.
Why we should pass the first parameter to set the value as we have set the future object before!?
Because the future object is an instance. The PropertyInfo is retrieved from the type (Type type = future.GetType();
) and isn't bound to any instance. That's why you have to pass the instance in the SetValue().
So:
var future = new Future();
var propertyName = "...";
Type type = future.GetType();
PropertyInfo propertyInfo = type.GetProperty(propertyName);
propertyInfo.SetValue(future, value);
You can reuse the propertyInfo to set properties of other instances.
Here
future.GetType()
future
was used only to obtain its type. Effectively it is the same as
Type t = future.GetType();
t.GetProperty(info.Name).SetValue(future, converted);
On the second line of the code above all the knowledge about what object was used to get the type is lost, and we are dealing with the type itself. Later, when we have information about the property of the type, we need to know what object it should be used with, so we are providing future
yet again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With