in Technology by

How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?

1 Answer

0 votes
by

Whilst the standard practice is to implement the ICloneable interface  here's a nice deep clone object copier I found on The Code Project a while ago and incorporated it in our stuff. As mentioned elsewhere, it requires your objects to be serializable.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
    /// <summary>
    /// Perform a deep Copy of the object.
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", nameof(source));
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}

The idea is that, it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex.

Related questions

0 votes
    Problem statement: An image A is projected through a projector, goes through a microscope and the projected ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    Fill in the blanks :- i. ____ means that the object is inserted as a copy of the original document. ii. ... to browse the internet. Select the correct answer from above options...
asked Dec 21, 2021 in Education by JackTerrance
0 votes
    It's a bit difficult to implement a deep object copy function. What steps you take to ensure the ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 27, 2022 in Education by JackTerrance
0 votes
    _______ means that the object is inserted as a copy of the original document. Select the correct answer from above options...
asked Dec 14, 2021 in Education by JackTerrance
0 votes
    I pulled a project from GitHub a few days ago. I've since discovered that there are several forks on GitHub, ... those forks I pulled? Select the correct answer from above options...
asked Feb 2, 2022 in Education by JackTerrance
0 votes
    Which of these modifiers can be used for a variable so that it can be accessed from any thread or parts of a ... O & Applets of Java Select the correct answer from above options...
asked Feb 24, 2022 in Education by JackTerrance
0 votes
    Constraint checking can be disabled in existing _______________ and _____________ constraints so that any data you ... Interview Questions and Answers for Freshers and Experience...
asked Oct 11, 2021 in Education by JackTerrance
0 votes
    The benefit of the _____ function is that it is the only way to perfectly repressed an R object in an ... Operations of R Programming Select the correct answer from above options...
asked Feb 13, 2022 in Education by JackTerrance
0 votes
    Can we make changes on the repo and how we can make sure that the same has been merged into the working copy?...
asked Feb 18, 2021 in Technology by JackTerrance
0 votes
    I am developing an application with Rails 3.0 and Backbone and I tried asset precompilation (rake assets: ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 12, 2022 in Education by JackTerrance
0 votes
    How can I remove this file from the repo without deleting my local copy of the file?...
asked Jan 8, 2021 in Technology by JackTerrance
0 votes
    Which of these method of Object class can clone an object? (a) Objectcopy() (b) copy() (c) ... java programming questions and answers pdf, java interview questions for beginners...
asked Oct 26, 2021 in Education by JackTerrance
0 votes
    Which of these transfer protocol must be used so that URL can be accessed by URLConnection class object? (a ... questions and answers pdf, java interview questions for beginners...
asked Oct 25, 2021 in Education by JackTerrance
0 votes
    After reading the chapter, I know these points: I know that data gets highlighted after being selected. I know ... entry and editing. Select the correct answer from above options...
asked Nov 26, 2021 in Education by JackTerrance
...