all groups > dotnet clr > february 2008 >
You're in the

dotnet clr

group:

setting Struct-s via Reflection


setting Struct-s via Reflection Edgile
2/27/2008 8:22:02 AM
dotnet clr:
Hello guys,

Due to special requirements, I must create my own
serialization/deserialization solution using .Net2.0. The idea looks straight
forward: I use Reflection to navigate through the objects and get/set their
fields (and also add/retrieve my own special stuff). However,
FieldInfo.Set(object obj, object value) does not work on Structs (see sample
code below). If I understand the things right, the underlying reason is that
structs are value types and passed by value. So in the body of FieldInfo.Set,
a copy of the input struct is set, while the original one outside the method
remains intact. Do you have any idea, how to overcome the issue? How does
BinarySerializer do that?

Here is an example:

System.Drawing.Point p = new System.Drawing.Point(10, 20);
FieldInfo xField = p.GetType().GetField("x", BindingFlags.Instance |

BindingFlags.NonPublic);
xField.SetValue(p, 100);
Console.WriteLine(p.X); // Still returns 10


Thanx in advance!




Re: setting Struct-s via Reflection Jon Skeet [C# MVP]
2/27/2008 4:32:47 PM
[quoted text, click to view]

Try this (untested):


System.Drawing.Point p = new System.Drawing.Point(10, 20);
FieldInfo xField = p.GetType().GetField("x", BindingFlags.Instance |

BindingFlags.NonPublic);

object[] boxed = new object[] {p};

xField.SetValue(boxed[0], 100);

p = (Point)boxed[0];
Console.WriteLine(p.X); // Still returns 10


--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button