How to Set Property Value using Reflection on a Value Type

by Zoran Horvat

It is sometimes needed to late bind object properties in order to set their values at run time without knowing at compile time which properties are going to be set. .NET Reflection helps obtain references to property descriptors (PropertyInfo objects) at run time and to set property values on a particular object. However, this principle might not work as expected when applied to value types.

Let's look at an example:

struct DemoStructure
{
    public int A { get; set; }
    public override string ToString()
    {
        return string.Format("{{A={0}}}", A);
    }
}


...

DemoStructure obj = new DemoStructure()
{
    A = 5
};

Console.WriteLine("obj={0}", obj);

obj.GetType().GetProperty("A").SetValue(obj, 10);

Console.WriteLine("obj={0}", obj);

When this piece of code is run, it produces an unexpected result:

            
obj={A=5}
obj={A=5}
                
    

This apparently indicates that PropertyInfo.SetValue did nothing with the property value. But this is only an illusion. Since obj variable is a value type, the instance received by the SetValue method is not the same instance as we see it when looking at the obj variable. It is rather a copy of obj, conveniently boxed to suit the SetValue method signature. That is the instance on which property was set. Unfortunately, this modification did not reflect back to the original obj variable and its property value has remained unchanged.

Solution to this problem is to take control over the boxing process. Here is the modified solution:

DemoStructure obj = new DemoStructure()
{
    A = 5
};

Console.WriteLine("obj={0}", obj);

object boxedObject = RuntimeHelpers.GetObjectValue(obj);

obj.GetType().GetProperty("A").SetValue(boxedObject, 10);

obj = (DemoStructure)boxedObject;

Console.WriteLine("obj={0}", obj);

In this case, the output looks as expected:

            
obj={A=5}
obj={A=10}
                
    

Explanation

PropertyInfo.SetValue method receives a System.Object as its first argument, and that is the instance on which property value should be set. When method call is made with a value type as an argument, the value must be boxed before the call is made. This process is performed transparently and what SetValue method effectively gets is a reference type which internally holds the value type instance. This value in turn is populated by performing a shallow copy of the original value instance.

Boxed reference type acts as a transparent proxy to the contained value type. Property getters and setters can be accessed as if the value type was never boxed. But after the fact, when boxed object goes out of scope, its contained value is going out of scope with it. Its property values are instantly forgotten.

The way out of problems is to copy the contained value back into the original object before the boxed object goes out of scope. But since its scope is the SetValue method, and since boxing was internally set up by the compiler, there seems to be no way to access the boxed object for the copying purposes.

To work around this obstacle, we are taking the responsibility to box the value type into our hands by using the RuntimeHelpers.GetObjectValue method. This method returns boxed value if its argument was a value type. Otherwise, if reference type is passed as the argument, GetObjetValue simply returns the input argument to its output. In this way, we get a hold of the boxed object, the one on which property value is modified. When changes are made to the underlying value instance, we are free to pick it up from the boxed object and to assign its contained values to the original object.

Critical part of the demo code above is this:

object boxedObject = RuntimeHelpers.GetObjectValue(obj);

obj.GetType().GetProperty("A").SetValue(boxedObject, 10);

obj = (DemoStructure)boxedObject;

In these three lines of code we are manually boxing the structure, performing the property late binding and then unboxing the modified object. And thanks to the flexible implementation of the RuntimeHelpers.GetObjectValue method, this piece of code works the same when obj is a reference type as well.


If you wish to learn more, please watch my latest video courses

About

Zoran Horvat

Zoran Horvat is the Principal Consultant at Coding Helmet, speaker and author of 100+ articles, and independent trainer on .NET technology stack. He can often be found speaking at conferences and user groups, promoting object-oriented and functional development style and clean coding practices and techniques that improve longevity of complex business applications.

  1. Pluralsight
  2. Udemy
  3. Twitter
  4. YouTube
  5. LinkedIn
  6. GitHub