Is this a good idea? (copying an object without implementing clone)

nismo

Member
Joined
Jun 30, 2006
Messages
18
Programming Experience
3-5
I cant remember where, but somebody gave me this peice of code to copy an instance of a class which does not have a clone method.

It works, but since i dont really understand it, i just want to know whether this is going to have any negative effects before i start using it more often... Also, will this function do a deep or shallow copy?



VB.NET:
    Public Function CopyObject(ByVal obj As Object) As Object
        'copies original object to stream then 
        'deserializes that stream and returns the output
        'to create clone (copy) of object

        Dim objMemStream As New MemoryStream(5000)


        Dim objBinaryFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter(Nothing, _
                     New Runtime.Serialization.StreamingContext(Runtime.Serialization.StreamingContextStates.Clone))

 

        objBinaryFormatter.Serialize(objMemStream, obj)

 

        objMemStream.Seek(0, SeekOrigin.Begin)

 

        CopyObject = objBinaryFormatter.Deserialize(objMemStream)

 

        objMemStream.Close()
    End Function
 
Last edited by a moderator:
i'm more interested to know in what situations would you copy objects> I dont recall doing much if any of it, in 10 years of programming
 
Whether or not that method has any negative impact would depend on the type. I'd think that in most cases it wouldn't but there may be some specific instances where it might.

If you want to be able to copy a type that doesn't have a Clone method then you should inherit it and provide one. Internally you simply call MemberwiseClone.

If you do go ahead and use that method then ask yourself what the difference between a shallow copy and a deep copy is. That method will copy everything that the object contains. If the object contains a reference to another object then that reference will be copied. Is that shallow or deep? How could it possible be the other?
 
Back
Top