Reputation: 6296
I have been reading here at stackoverflow how to write to a class var member using reflection. I use something like:
typeof(MyClass).GetField("myvar", BindingFlags.Public | BindingFlags.Instance).SetValue(instancie, 10);
This works for classes but if I do the same for a Struct instead of a class when reading myvar I allways get 0 (default construction value for int). This is the code I use:
struct MyStruct
{
public int myvar;
}
MyStruct instance=new MyStruct();
typeof(MyStruct).GetField("myvar", BindingFlags.Public | BindingFlags. BindingFlags.Instance).SetValue(instance, 10);
Do anybody know why could this be hapenning?
Upvotes: 4
Views: 211
Reputation: 1064114
When you pass in "instance", that is a box - which is a wrapped clone of the data, that you later discard.
To use reflection here:
object obj = instance; // box
blah.SetValue(obj, value); // mutate inside box
instance = (YourType)obj; // unbox
Upvotes: 5