Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetValue in reflection in c#

Tags:

c#

reflection

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!?

like image 238
Pooya Yazdani Avatar asked Aug 12 '13 07:08

Pooya Yazdani


2 Answers

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.

like image 75
Jeroen van Langen Avatar answered Oct 10 '22 16:10

Jeroen van Langen


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.

like image 37
Andrei Avatar answered Oct 10 '22 17:10

Andrei