by Zoran Horvat
Reflection lets us set values of the properties without knowing actual properties, or even objects at compile time. But getting hold of property descriptors (PropertyInfo instances) may sometimes be a cumbersome task.
LINQ to Objects comes as a rescue when multiple properties need to be isolated from a given object. The code which includes LINQ query is easier to write and more readable than the code based on loops.
The following function accepts an object and a collection of name/value pairs, each pair representing one property returning integer value. Function finds all listed properties in the object and then sets their values.
T RehydrateObject<T>(T obj, IEnumerable<Tuple<string, int>> nameValues)
{
object boxedCopy = RuntimeHelpers.GetObjectValue(obj);
var propertyDescriptors =
(from property in typeof(T).GetProperties()
join nameValuePair in nameValues on property.Name equals nameValuePair.Item1
select new
{
Property = property,
Value = nameValuePair.Item2
});
foreach (var pd in propertyDescriptors)
pd.Property.SetValue(boxedCopy, pd.Value);
obj = (T)boxedCopy;
return obj;
}
Observe the way in which received object was first boxed. This trick ensures that the function works fine with value types as well as with reference types. Please refer to How to Set Property Value using Reflection on a Value Type for details on this issue.
On a related note, name/value pairs collection used in this example was returned by DehydrateObject function, which is explained in How to Get Property Values using LINQ to Objects .
Below is the source code of a console application which demonstrates the RehydrateObject method. When function listed above is applied to an instance of the Rectangle structure (value type), it extracts four integer properties from the collection and sets the corresponding Rectangle properties. In the second part of the test, function is applied to a class (reference type) and another collection of name/value pairs. In both cases, the rehydrated objects will have their properties set to values listed in the collection.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
namespace PropertySettingDemo
{
class Program
{
static T RehydrateObject<T>(T obj, IEnumerable<Tuple<string, int>> nameValues)
{
...
}
class DemoClass
{
public int A { get; set; }
public int B { get; set; }
public override string ToString()
{
return string.Format("{{A={0},B={1}}}", A, B);
}
}
static void Main(string[] args)
{
Tuple<string, int>[] values = new Tuple<string, int>[]
{
new Tuple<string, int>("X", 20),
new Tuple<string, int>("Y", 30),
new Tuple<string, int>("Width", 150),
new Tuple<string, int>("Height", 90)
};
Rectangle rect = RehydrateObject<Rectangle>(new Rectangle(), values);
Console.WriteLine("Rectangle={0}", rect);
values = new Tuple<string, int>[]
{
new Tuple<string, int>("A", 70),
new Tuple<string, int>("B", 80)
};
DemoClass c = RehydrateObject<DemoClass>(new DemoClass(), values);
Console.WriteLine("DemoClass={0}", c);
Console.Write("Press ENTER to continue... ");
Console.ReadLine();
}
}
}
When application is run, it produces output like this:
Rectangle={X=20,Y=30,Width=150,Height=90}
DemoClass={A=70,B=80}
Press ENTER to continue...
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.