Copy an object in c#

Posted on 2007-10-11
Last Modified: 2009-01-23
OK, this should be easy but I'm stuck

I have an object created in c# say Object1.  I need to temporarily back up this object to another object say ObjectOriginal.

However if I do ObjectOriginal = Object1, any changes to Object 1 affect ObjectOriginal.  How do I go about this?
Question by:dbdp
    LVL 21

    Accepted Solution

    Do a deep copy of the object. Because assignment doesnt copy the value but just copies the reference, so if you delete one, you delete the other.

    If the object has a few properties i would suggest creating a new object and copying it property by property otherwise use deep copy. This uses XML serializer to make a copy, you could consider using a binary serializer to achieve the same.

            /// <summary>
            /// Copies the object instance of a particular type to the destination type.
            /// </summary>
            /// <param name="source">The Type of the source object instance.</param>
            /// <param name="sourceToCopy">The actual instance to be coverted to destination type.</param>
            /// <param name="destination">The desination Type to which the source object instance needs
            /// to be comverted.</param>
            /// <returns>An object instance of the destination type.</returns>
            public object Copy(Type source, object sourceToCopy, Type destination)
                XmlSerializer serializer = new XmlSerializer(source);
                MemoryStream memoryStream = new MemoryStream();

                XmlSerializerNamespaces nameSpacesList = new XmlSerializerNamespaces();
                nameSpacesList.Add("", "");

                serializer.Serialize(memoryStream, sourceToCopy, nameSpacesList);

                byte[] byteArr = memoryStream.ToArray();
                ASCIIEncoding encoder = new ASCIIEncoding();
                string xmlString = encoder.GetString(byteArr);

                ASCIIEncoding newEncoder = new ASCIIEncoding();
                byte[] newByteArr = newEncoder.GetBytes(xmlString);
                MemoryStream newMemoryStream = new MemoryStream(newByteArr);

                XmlSerializer deSer = new XmlSerializer(destination);

                object deserializedObject = deSer.Deserialize(newMemoryStream);

                return deserializedObject;

    LVL 29

    Assisted Solution

    by:Gautham Janardhan
    u could use the xml serializer but the proble with xml serializer is that ur variable should be either oublic or should have properties with get/set. so the very concept or protecting of ur variable goes bizzard..
    another option is to use the binary serializer

                    IFormatter formatter = new BinaryFormatter();
                    Stream FWriter =
                        new MemoryStream();
                    formatter.Serialize(FWriter, objecttobeserialized);

    to deserialize...

    IFormatter formatter = new BinaryFormatter();
                object DataCopy = formatter.Deserialize(FWriter);
    ck(sender, e);
    LVL 26

    Assisted Solution

    by:Anurag Thakur
    you need to do a deep copy for creating a copy of the object
    C# does not support copy constructors as C++ but this article from MSDN will help you in creating a copy constructor
    I hope this helps in solving your problem.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Suggested Solutions

    This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
    We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now