merging two objects in C#

Update Use AutoMapper instead if you need to invoke this method a lot. Automapper builds dynamic methods using Reflection.Emit and will be much faster than reflection.'

You could copy the values of the properties using reflection:

public void CopyValues<T>(T target, T source)
{
    Type t = typeof(T);

    var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);

    foreach (var prop in properties)
    {
        var value = prop.GetValue(source, null);
        if (value != null)
             prop.SetValue(target, value, null);
    }
}

I've made it generic to ensure type safety. If you want to include private properties you should use an override of Type.GetProperties(), specifying binding flags.


I have tried Merge Two Objects into an Anonymous Type by Kyle Finley and it is working perfect.

With the TypeMerger the merging is as simple as

var obj1 = new {foo = "foo"};

var obj2 = new {bar = "bar"};

var mergedObject = TypeMerger.MergeTypes(obj1 , obj2 );

That's it you got the merged object, apart from that, there is a provision to ignore specific properties too. You can use the same thing for MVC3 too.


You can do it using reflection, but as someone stated, it'll have a performance penalty.

Since you're working with an expected class design, you can achieve the same goal by using an extension method like so:

public static class MyClassExtensions
{
    public static void Merge(this MyClass instanceA, MyClass instanceB)
    {
        if(instanceA != null && instanceB != null)
        {
             if(instanceB.Prop1 != null) 
             {
                 instanceA.Prop1 = instanceB.Prop1;
             }


             if(instanceB.PropN != null) 
             {
                 instanceA.PropN = instanceB.PropN;
             }
    }
}

And later, somewhere in your code:

someInstanceOfMyClass.Merge(someOtherInstanceOfMyClass);

At the end of the day you've centralized this operation in an extension method and if you add or remove a property of your class, you only need to modify extension method's implementation and you'll get everything done.

Tags:

C#

.Net