Reflection

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

Mattias Sjögren

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
 
A

Andrew

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
 
J

Jon Skeet [C# MVP]

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.
 
G

Guest

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
.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top