Writing a value to a struct var element with reflection does not work, but for classes

I read here on stackoverflow how to write a member of the var class using reflection. I am using something like:

typeof(MyClass).GetField("myvar", BindingFlags.Public | BindingFlags.Instance).SetValue(instancie, 10); 

This works for classes, but if I do the same for Struct instead of a class when reading myvar, I always get 0 (default value for int). This is the code I'm using:

 struct MyStruct { public int myvar; } MyStruct instance=new MyStruct(); typeof(MyStruct).GetField("myvar", BindingFlags.Public | BindingFlags. BindingFlags.Instance).SetValue(instance, 10); 

Does anyone know why this could happen?

+4
source share
1 answer

When you pass in an instance, this field is a wrapped data clone that you later discard.

To use reflection here:

 object obj = instance; // box blah.SetValue(obj, value); // mutate inside box instance = (YourType)obj; // unbox 
+5
source

Source: https://habr.com/ru/post/1401857/


All Articles