0

I'm trying to find the best way to make copies of a pretty big class. It has somewhere around 80 properties. I could of course code them all in a normal copy constructor, but I'm not sure how nice that would look in code.

So I'm thinking... Is there a way to iterate through the properties of obj A and assign the the values to the corresponding properties of obj B?

This queston is marked as a duplicate, but it is not. My question is not how to make a deep copy, the question is how to iterate through the properties and thus make a normal copy constructor with many properties.

Christoffer
  • 7,470
  • 9
  • 39
  • 55

1 Answers1

4

Here is one way:

public static T DeepClone<T>(T original)
{
    if (!typeof(T).IsSerializable)
    {
        throw new ArgumentException("The type must be serializable.", "original");
    }

    if (ReferenceEquals(original, null))
    {
        return default(T);
    }

    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter
        {
            Context = new StreamingContext(StreamingContextStates.Clone)
        };

        formatter.Serialize(stream, original);
        stream.Position = 0;

        return (T) formatter.Deserialize(stream);
    }
}

This is adapted from CLR via C# by Jeffrey Richter.

You use it like this:

var objB = DeepClone(objA);

The type must be serializable for this to work, though.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • 2
    I have never seen the [streaming context](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.streamingcontext.context.aspx) set before when doing this method. Why is that done and what does it provide? – Scott Chamberlain Jun 17 '13 at 20:12
  • @Sayse No, I took it from `CLR via C#` like I said in my answer! :) – Matthew Watson Jun 17 '13 at 20:13
  • @Sayse and that answer was likely adapted from the book [CLR via C#](http://www.amazon.com/CLR-via-C-Developer-Reference/dp/0735667454) (like Matthew said) – Scott Chamberlain Jun 17 '13 at 20:13
  • 1
    @ScottChamberlain The streaming context `Clone` tells it that an in-process copy is being made, which could allow it to clone unmanaged handles better: `"Specifies that the object graph is being cloned. Users can assume that the cloned graph will continue to exist within the same process and be safe to access handles or other references to unmanaged resources. "` But I confess, I'm not really sure *what* that means! I think I'll post a question about it. :) – Matthew Watson Jun 17 '13 at 20:15
  • Thank you. I will see if this might be the solution for me. I looks really slick. Kudos and upvotes for a very nice and comprehensive answer! – Christoffer Jun 18 '13 at 09:52