Reflection

  • Thread starter Thread starter Andrew
  • Start date Start date
A

Andrew

I cannot figure out why I cannot change the struct value
in the following reflective code...
///////////////////////////////////////////////////////
class MyClass
{

public struct mys
{
public string mystring;
}

static void Main(string[] argv)
{

mys s = new mys();

Type t = s.GetType();
t.GetField("mystring").SetValue
(s, "hello world");
}
}
///////////////////////////////////////////////////////

Any help appreciated... Thanks!!!
 
The problem is that the struct is being boxed in the call to SetValue,
and you end up modifying the boxed copy. To get the changes back, you
have to do

object tmp = s;
t.GetField("mystring").SetValue(tmp, "hello world");
s = (mys)tmp;



Mattias
 
Thanks! That worked, but I still don't understand why.

Why would it be necessary to create that 'tmp' reference?
I suppose I don't know what you mean by "being boxed". Is
it something to do with the struct being a value type?

Thanks again,

Andrew
 
Andrew said:
Thanks! That worked, but I still don't understand why.

Why would it be necessary to create that 'tmp' reference?
I suppose I don't know what you mean by "being boxed". Is
it something to do with the struct being a value type?

Yes, it's absolutely to do with the struct being a value type. Boxing occurs
when you need a reference, but you've got a value type value.

Rather than give you half the story on boxing, I suggest you look up
boxing in the MSDN.
 
I will, thanks for the help.

Andrew
-----Original Message-----


Yes, it's absolutely to do with the struct being a value type. Boxing occurs
when you need a reference, but you've got a value type value.

Rather than give you half the story on boxing, I suggest you look up
boxing in the MSDN.

--
Jon Skeet - <[email protected]>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
.
 
Back
Top