Combining Objects in C#

There has been a few times I’ve need to copy models to view models, or very similar classes to each other, but wanted to clean up the code in the process. The result of that is a start to a helper method below to “combine” objects in C#. Code will stay static on this post. To retrieve updated code, visit via GitHub.

1public static class ObjectJoin
2    {
3        /// <summary>
4        /// Attempts to combine values from two different objects with the same property names into one object
5        /// </summary>
6        /// <param name="firstObject">The object in which we will return with combined values</param>
7        /// <param name="secondObject">The object in which we will be pulling values from</param>
8        /// <param name="sourceOverwrite">If we overwrite the value from the first object if one already exists (Default is true)</param>
9        /// <returns>The first object with combined values from the second object</returns>
10        public static object JoinObjects(object firstObject, object secondObject, bool sourceOverwrite = true)
11        {
12            if(firstObject == null || secondObject == null)
13            {
14                throw new ArgumentException("One of the objects passed to JoinObjects is null");
15            }
16 
17            // Read in first object information
18            var firstObjectHash = GetObjectPropertyHash(firstObject);
19 
20            // Read in the second object information
21            var secondObjectHash = GetObjectPropertyHash(secondObject);
22 
23            foreach (var item in firstObjectHash)
24            {
25                if (secondObjectHash.ContainsKey(item.Key) && (secondObjectHash[item.Key] != null || sourceOverwrite))
26                {
27                    SetObjectProperty(ref firstObject, item.Key, secondObjectHash[item.Key]);
28                }               
29            }
30            return firstObject;
31        }
32 
33        /// <summary>
34        /// Retrieves the parameter and value list of an inputed object
35        /// </summary>
36        /// <param name="obj">The object which to identify the properties and values</param>
37        /// <returns>A dictionary of the parameter names as the key, and property values as values</returns>
38        private static Dictionary<string,object> GetObjectPropertyHash(object obj)
39        {
40            Type objType = obj.GetType();
41            Dictionary<string, object> hashTable = new Dictionary<string, object>();
42            foreach (PropertyInfo property in objType.GetProperties())
43            {
44                hashTable.Add(property.Name, property.GetValue(obj, null));
45            }
46            return hashTable;
47        }
48 
49        /// <summary>
50        /// Attempts to set a value to a property dynamically
51        /// </summary>
52        /// <param name="obj">The object which you are dynamically setting a property to</param>
53        /// <param name="propertyName">The name of the objects property to assign the value to</param>
54        /// <param name="value">The value to assign to the object's property</param>
55        private static void SetObjectProperty(ref object obj, string propertyName, object value)
56        {
57            PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);           
58            if (propertyInfo != null && value != null && propertyInfo.GetSetMethod() != null)
59            {
60                try
61                {
62                    if (value.GetType().GetInterface("IConvertible") != null)
63                    {
64                        value = value.GetType().FullName == propertyInfo.PropertyType.FullName ? value : Convert.ChangeType(value, propertyInfo.PropertyType);
65                        propertyInfo.SetValue(obj, value);
66                    }
67                }
68                catch
69                {
70                    throw new Exception(string.Format("An error occurred when attempting to set the value of {0} of type {1}", propertyName, obj.ToString()));
71                }
72            }
73        }
74    }

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: