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}
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
In this course, you will learn the basic principles of object-oriented programming, and then learn how to apply those principles to construct an operational and correct code using the C# programming language and .NET.
As the course progresses, you will learn such programming concepts as objects, method resolution, polymorphism, object composition, class inheritance, object substitution, etc., but also the basic principles of object-oriented design and even project management, such as abstraction, dependency injection, open-closed principle, tell don't ask principle, the principles of agile software development and many more.
More...
In this course, you will learn how design patterns can be applied to make code better: flexible, short, readable.
You will learn how to decide when and which pattern to apply by formally analyzing the need to flex around specific axis.
More...
This course begins with examination of a realistic application, which is poorly factored and doesn't incorporate design patterns. It is nearly impossible to maintain and develop this application further, due to its poor structure and design.
As demonstration after demonstration will unfold, we will refactor this entire application, fitting many design patterns into place almost without effort. By the end of the course, you will know how code refactoring and design patterns can operate together, and help each other create great design.
More...
In four and a half hours of this course, you will learn how to control design of classes, design of complex algorithms, and how to recognize and implement data structures.
After completing this course, you will know how to develop a large and complex domain model, which you will be able to maintain and extend further. And, not to forget, the model you develop in this way will be correct and free of bugs.
More...
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.