Search code examples
c#ooprecursionreflectionpropertyinfo

How to set reflected property value stored as object?


I would like to set a value of a property of a reflected object, but I cannot refer to the object itself. I have the property stored as System.object- that's all.

class Painting
{
   public System.Color PaintingColor;
   {
       get { return m_color; }
       set { m_color = value; }
   }
}

Basing on the example - I have an object of type System.Color, which is actually a property value of a Painting I have created via reflection. I would like to do:

object pnt = //initialized with Activator.CreateInstance
pnt.GetType().GetProperty("PaintingColor").SetValue(pnt, Color.Black);

However, due to recursion I'm using, I only have:

object clr = pnt.GetType().GetProperty("PaintingColor").GetValue();

with no access to pnt. Is it possible to change the clr so it actually changes the property value of pnt? Obviously, clr = Color.Black doesn't work.


Solution

  • All you are getting in your code is the actual value of the property; not a reference or pointer that you could use to actually assign it.

    If the value you got was mutable then you could change properties on that object and it would propagate, but that doesn't apply to System.Color.

    If you really need to do this, I would suggest changing the property to a wrapper around System.Color so you can change the internal variable. Generally speaking though, the need to do this indicates you are probably not doing it right.