Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Copy an instance

Copy an instance

Scheduled Pinned Locked Moved C#
question
12 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    sjembek
    wrote on last edited by
    #1

    Is it possible to make an exact copy of an instance of an object (not its reference)? This is what I'd like to achieve: 1 make a copy of an instance at a certain moment to save the state it's in 2 modify the original for a bit 3 replace the original object with the saved one later on This way I'd like to be able to "recall" the state my object was in at the moment I made a copy. Is this possible without manually constructing a new object of this type and copying all of it's members?

    D A L J L 5 Replies Last reply
    0
    • S sjembek

      Is it possible to make an exact copy of an instance of an object (not its reference)? This is what I'd like to achieve: 1 make a copy of an instance at a certain moment to save the state it's in 2 modify the original for a bit 3 replace the original object with the saved one later on This way I'd like to be able to "recall" the state my object was in at the moment I made a copy. Is this possible without manually constructing a new object of this type and copying all of it's members?

      D Offline
      D Offline
      Dustin Metzgar
      wrote on last edited by
      #2

      To do this, you can binary serialize the object. Serialize the object to a memory stream and then deserialize to a new instance. For classes that don't have a CopyTo method, this is pretty helpful. However, the class that you're serializing has to have the Serializable attribute.


      Logifusion[^] If not entertaining, write your Congressman.

      S 1 Reply Last reply
      0
      • S sjembek

        Is it possible to make an exact copy of an instance of an object (not its reference)? This is what I'd like to achieve: 1 make a copy of an instance at a certain moment to save the state it's in 2 modify the original for a bit 3 replace the original object with the saved one later on This way I'd like to be able to "recall" the state my object was in at the moment I made a copy. Is this possible without manually constructing a new object of this type and copying all of it's members?

        A Offline
        A Offline
        A A 0
        wrote on last edited by
        #3

        In short you want something to that gives you an 'undo' feature. I don't like recommending 'design patterns' without looking at several alternatives, but in this case the Memento pattern fits well. Googling will give you a solid explanation. Wikipedia has a short code sample: Memento pattern[^]

        Recitation(not full prayer)in AlMasjid AlHaram Surah AlHaaqa(The Reality) Surah Qaf Eid Alfitr Turning Muslim in Texas?

        S 1 Reply Last reply
        0
        • S sjembek

          Is it possible to make an exact copy of an instance of an object (not its reference)? This is what I'd like to achieve: 1 make a copy of an instance at a certain moment to save the state it's in 2 modify the original for a bit 3 replace the original object with the saved one later on This way I'd like to be able to "recall" the state my object was in at the moment I made a copy. Is this possible without manually constructing a new object of this type and copying all of it's members?

          L Offline
          L Offline
          LongRange Shooter
          wrote on last edited by
          #4

          You could do the following: Make the following changes to your class:

          public class MyClass : ICloneable
          {
          public MyClass(){}
          public MyClass(object newInstance)
          {
          if ( !(newInstance is MyClass) ) throw new Exception...
          MyClass instance = (MyClass)newInstance;
          // set all properties to the values in the passed instance
          }
          public object Clone
          {
          return (object)this;
          {
          }

          Then in your code you would do as follows:

          ...
          MyClass newObject = new MyClass(oldObject.Clone());
          

          Unfortunately, there is no ICloneable and object is all you can pass.

          1 Reply Last reply
          0
          • S sjembek

            Is it possible to make an exact copy of an instance of an object (not its reference)? This is what I'd like to achieve: 1 make a copy of an instance at a certain moment to save the state it's in 2 modify the original for a bit 3 replace the original object with the saved one later on This way I'd like to be able to "recall" the state my object was in at the moment I made a copy. Is this possible without manually constructing a new object of this type and copying all of it's members?

            J Offline
            J Offline
            Judah Gabriel Himango
            wrote on last edited by
            #5

            Wesner Moise has a good blog posting[^] regarding how to clone objects that don't implement ICloneable. He basically uses reflection to invoke the protected MemberwiseClone method. If you have the source code to this object, I'd just make it implement ICloneable.

            Tech, life, family, faith: Give me a visit. I'm currently blogging about: Messianic Instrumentals (with audio) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

            S 1 Reply Last reply
            0
            • A A A 0

              In short you want something to that gives you an 'undo' feature. I don't like recommending 'design patterns' without looking at several alternatives, but in this case the Memento pattern fits well. Googling will give you a solid explanation. Wikipedia has a short code sample: Memento pattern[^]

              Recitation(not full prayer)in AlMasjid AlHaram Surah AlHaaqa(The Reality) Surah Qaf Eid Alfitr Turning Muslim in Texas?

              S Offline
              S Offline
              sjembek
              wrote on last edited by
              #6

              I see the use of the pattern, but it seems this will only work for a single member that defines the state, while I meant the state of the object itself and all of its members... I'm afraid this won't work, but thanks for the info.

              1 Reply Last reply
              0
              • D Dustin Metzgar

                To do this, you can binary serialize the object. Serialize the object to a memory stream and then deserialize to a new instance. For classes that don't have a CopyTo method, this is pretty helpful. However, the class that you're serializing has to have the Serializable attribute.


                Logifusion[^] If not entertaining, write your Congressman.

                S Offline
                S Offline
                sjembek
                wrote on last edited by
                #7

                Actually it is Serializable since it can be stored to disk too. I just had a go with this but I haven't serialized to memory before and for some reason I'm getting a System.Runtime.Serialization.SerializationException: End of Stream encountered before parsing was completed. The code looks like this.

                Collection myOutputCollection = new Collection();

                BinaryFormatter bFormatter = new BinaryFormatter();

                MemoryStream mStream = new MemoryStream();
                OutputData myOutput;

                bFormatter.Serialize(mStream, myOutput);

                deserializedOutput = (OutputData)bFormatter.Deserialize(mStream);

                myOutputCollection.add(deserializedOutput);

                mStream.Close();

                I'm serializing and deserializing the object, then adding it to a collection, since I'm still using it from the collection once it's added (it's not like I don't need it anymore).

                D 1 Reply Last reply
                0
                • J Judah Gabriel Himango

                  Wesner Moise has a good blog posting[^] regarding how to clone objects that don't implement ICloneable. He basically uses reflection to invoke the protected MemberwiseClone method. If you have the source code to this object, I'd just make it implement ICloneable.

                  Tech, life, family, faith: Give me a visit. I'm currently blogging about: Messianic Instrumentals (with audio) The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                  S Offline
                  S Offline
                  sjembek
                  wrote on last edited by
                  #8

                  Looks interesting, I'll try this out...

                  S 1 Reply Last reply
                  0
                  • S sjembek

                    Actually it is Serializable since it can be stored to disk too. I just had a go with this but I haven't serialized to memory before and for some reason I'm getting a System.Runtime.Serialization.SerializationException: End of Stream encountered before parsing was completed. The code looks like this.

                    Collection myOutputCollection = new Collection();

                    BinaryFormatter bFormatter = new BinaryFormatter();

                    MemoryStream mStream = new MemoryStream();
                    OutputData myOutput;

                    bFormatter.Serialize(mStream, myOutput);

                    deserializedOutput = (OutputData)bFormatter.Deserialize(mStream);

                    myOutputCollection.add(deserializedOutput);

                    mStream.Close();

                    I'm serializing and deserializing the object, then adding it to a collection, since I'm still using it from the collection once it's added (it's not like I don't need it anymore).

                    D Offline
                    D Offline
                    Dustin Metzgar
                    wrote on last edited by
                    #9

                    Before you deserialize, you have to rewind the memory stream back to the initial position.


                    Logifusion[^] If not entertaining, write your Congressman.

                    S 1 Reply Last reply
                    0
                    • D Dustin Metzgar

                      Before you deserialize, you have to rewind the memory stream back to the initial position.


                      Logifusion[^] If not entertaining, write your Congressman.

                      S Offline
                      S Offline
                      sjembek
                      wrote on last edited by
                      #10

                      This works, thx :)

                      1 Reply Last reply
                      0
                      • S sjembek

                        Looks interesting, I'll try this out...

                        S Offline
                        S Offline
                        sjembek
                        wrote on last edited by
                        #11

                        Works perfectly... Thank you.

                        1 Reply Last reply
                        0
                        • S sjembek

                          Is it possible to make an exact copy of an instance of an object (not its reference)? This is what I'd like to achieve: 1 make a copy of an instance at a certain moment to save the state it's in 2 modify the original for a bit 3 replace the original object with the saved one later on This way I'd like to be able to "recall" the state my object was in at the moment I made a copy. Is this possible without manually constructing a new object of this type and copying all of it's members?

                          L Offline
                          L Offline
                          Libor Tinka
                          wrote on last edited by
                          #12

                          I'm doing this using the Clone method of the object. I think there's no universal mechanism for copying objects, so you need to implement this method by your own. If you are working with more types, it is good to use some ICloneable interface. This is an example: public interface ICloneable { object Clone(); } public class BitmapWithArray : ICloneable { public Bitmap bitmap = null; public int[] array = null; public ushort someValue = 0; public object Clone() { BitmapWithArray obj = new BitmapWithArray(); if (this.bitmap != null) obj.bitmap = (Bitmap)this.bitmap.Clone(); if (this.array != null) obj.array = (int[])this.array.Clone(); obj.someValue = this.someValue; // this is a value type, no copies needed } }

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups