C# reflection doesn't work with Point class?

I can't figure out what I am doing wrong. I've got this code:

Point p = new Point();
//point is (0,0)
p.X = 50;
//point is (50,0)
PropertyInfo temp = p.GetType().GetProperty("X");
temp.SetValue(p, 100, null);
//and point is still (50,0)
MethodInfo tt = temp.GetSetMethod();
tt.Invoke(p, new object[] { 200 });
//still (50,0)

Why?

I was looking for answer, but I have found nothing.

Jon Skeet
people
quotationmark

Ah, the joys of mutable structs. As Sergey said, Point is a struct. When you're calling PropertyInfo.SetValue, you're taking the value of p, boxing it (which copies the value), modifying the contents of the box... but then ignoring it.

You can still use reflection with it - but importantly, you only want to box it once. So this works:

object boxed = p;
PropertyInfo temp = p.GetType().GetProperty("X");
temp.SetValue(boxed, 100, null);
Console.WriteLine(boxed); // {X=100, Y=0}
MethodInfo tt = temp.GetSetMethod();
tt.Invoke(boxed, new object[] { 200 });
Console.WriteLine(boxed); // {X=200, Y=0}

Note that this won't change the value of p, but you can unbox it again afterwards:

object boxed = p;
property.SetValue(boxed, ...);
p = (Point) boxed;

people

See more on this question at Stackoverflow