[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Copy an object in c#

Posted on 2007-10-11
3
Medium Priority
?
16,721 Views
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?
0
Comment
Question by:dbdp
3 Comments
 
LVL 21

Accepted Solution

by:
surajguptha earned 800 total points
ID: 20058177
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;

        }
0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 600 total points
ID: 20063361
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);
                FWriter.Flush();
                FWriter.Close();

to deserialize...

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

Assisted Solution

by:Anurag Thakur
Anurag Thakur earned 600 total points
ID: 20064950
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
http://msdn2.microsoft.com/en-us/library/ms173116(VS.80).aspx
I hope this helps in solving your problem.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Screencast - Getting to Know the Pipeline
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

831 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