Christoffer
Christoffer

Reputation: 7787

Automate a copy constructor in C#

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.

Upvotes: 1

Views: 446

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109792

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.

Upvotes: 5

Related Questions