Why does reflection not reflect a property in Struct?

class PriceClass { private int value; public int Value { get { return this.value; } set { this.value = value; } } } struct PriceStruct { private int value; public int Value { get { return this.value; } set { this.value = value; } } } static void Main(string[] args) { PriceClass _priceClass = new PriceClass(); Type type = typeof(PriceClass); PropertyInfo info = type.GetProperty("Value"); info.SetValue(_priceClass, 32, null); Console.WriteLine(_priceClass.Value); PriceStruct _priceStruct = new PriceStruct(); type = typeof(PriceStruct); info = type.GetProperty("Value"); info.SetValue(_priceStruct, 32, null); Console.WriteLine(_priceStruct.Value); Debugger.Break(); } 

The first value printed is 32 and the second is 0. No exception thrown

+8
reflection struct properties
source share
3 answers

This is because the box of your structure makes a copy of it, so you must put it earlier so that you call the receiver from the same data that you changed. The following code works:

  object _priceStruct = new PriceStruct(); //Box first type = typeof(PriceStruct); info = type.GetProperty("Value"); info.SetValue(_priceStruct, 32, null); Console.WriteLine(((PriceStruct)_priceStruct).Value); //now unbox and get value Debugger.Break(); 
+12
source share

structs are ValueTypes that are passed by value, which means that you only pass copies of the entire structure, not a reference to the original object.

So when you pass it to info.SetValue(_priceStruct, 32, null) , the method passed to the method and mutated, so the original object does not change at all. Another reason why mutable structures are evil.

+4
source share

You can still change them using reflection, but it's a little longer.

See this example: http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/2dd4315c-0d0d-405c-8d52-b4b176997472

+1
source share

All Articles