http://www.codinghelmet.com/  

Wear a helmet. Even when coding.

hints > value-type-property-setting

How to Set Property Value using Reflection on a Value Type
by Zoran Horvat @zoranh75

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.

See also:

Published: Aug 6, 2013

ZORAN HORVAT

Zoran is software architect dedicated to clean design and CTO in a growing software company. Since 2014 Zoran is an author at Pluralsight where he is preparing a series of courses on object-oriented and functional design, design patterns, writing unit and integration tests and applying methods to improve code design and long-term maintainability.

Follow him on Twitter @zoranh75 to receive updates and links to new articles.

Watch Zoran's video courses at pluralsight.com (requires registration):

Making Your C# Code More Object-Oriented

This course will help leverage your conceptual understanding to produce proper object-oriented code, where objects will completely replace procedural code for the sake of flexibility and maintainability. More...

Advanced Defensive Programming Techniques

This course will lead you step by step through the process of developing defensive design practices, which can substitute common defensive coding, for the better of software design and implementation. More...

Tactical Design Patterns in .NET: Creating Objects

This course sheds light on issues that arise when implementing creational design patterns and then provides practical solutions that will make our code easier to write and more stable when running. More...

Tactical Design Patterns in .NET: Managing Responsibilities

Applying a design pattern to a real-world problem is not as straight-forward as literature implicitly tells us. It is a more engaged process. This course gives an insight to tactical decisions we need to make when applying design patterns that have to do with separating and implementing class responsibilities. More...

Tactical Design Patterns in .NET: Control Flow

Improve your skills in writing simpler and safer code by applying coding practices and design patterns that are affecting control flow. More...

Writing Highly Maintainable Unit Tests

This course will teach you how to develop maintainable and sustainable tests as your production code grows and develops. More...

Improving Testability Through Design

This course tackles the issues of designing a complex application so that it can be covered with high quality tests. More...

Share this article

webmasters