Copy of object

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

How can I create a method that returns a copy of an object, not a reference to the object itself.

Thanks !

Heinz
 
Hi Heinz,

Depends on the class.
Normally you might want to use ICloneable.Clone method which might in turn
invoke protected MemberwiseClone method that creates a shallow copy.
Another way would be to serialize the object to a memory stream and
deserialize it - you'll end up with deep copy. Of course, all involved
classes will have to support serialization.
But ... it really depends on the class.

--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

Heinz said:
Hi all,

How can I create a method that returns a copy of an object, not a
reference to the object itself.
 
I use the following method - accepts any object whose class is marked
'serializable'. If you want a shallow copy, which is what I usually
use, mark the object references of the class you're copying as
non-serializable and copy the references separately after calling
CloneObject:

internal static object CloneObject(object oObject)
{
//returns a separate object with all serializable
//properties set to those of oObject (the object class
//must have the "Serializable" attribute)
System.IO.MemoryStream oStream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
oFormatter = new
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
oFormatter.Serialize(oStream, oObject);
oStream.Seek(0, System.IO.SeekOrigin.Begin);
return oFormatter.Deserialize(oStream);
}
 
Back
Top