Class1 = Class2 Want to actually copy not make refernce to.....

VB.NET

Hello,
I am having a problem with copying one class into another. In the following example I have declared to instances of the same class.
When I Make one = another they become linked. So if I change TopClass at all BottomClass changes as well. I don't want BottomClass to be a reference to TopClass, I just want to copy the data as it is at that instant.



Dim TopClass As New Class1
Dim BottomClass As New Class1


BottomClass = TopClass


But I don't want to go through and do...

BottomClass.First = TopClass.First
BottomClass.Last= TopClass.Last

which would keep that from happening.

Emotion

Comments

  • [b][red]This message was edited by iwilld0it at 2003-12-16 6:40:12[/red][/b][hr]
    You can implement a cloning scheme in your class. here is an example ...

    [code]
    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary

    _
    Public Class SomeClass
    Implements ICloneable

    Public Name As String

    Public Function Clone() As SomeClass
    Return CType(CloneIt(), SomeClass)
    End Function

    Private Function CloneIt() As Object Implements System.ICloneable.Clone
    Dim ms As New MemoryStream
    Dim bf As New BinaryFormatter
    bf.Serialize(ms, Me)
    ms.Seek(0, SeekOrigin.Begin)
    CloneIt = bf.Deserialize(ms)
    ms.Close()
    End Function
    End Class
    [/code]


    Now you can clone your objects like so ...

    [code]
    Dim sc1 As New SomeClass
    sc1.Name = "Mike"

    Dim sc2 As SomeClass = sc1.Clone
    sc2.Name = "Tom"

    Debug.WriteLine(sc1.Name) ' Mike
    Debug.WriteLine(sc2.Name) ' Tom
    [/code]

    It is important that you mark your class as serializable because the Clone function uses serialization to create a deep copy of the object. Basically the Clone function creates a temporary memory stream, serializes the current object to that stream, rewinds the stream, and then deserializes. The deserialized object in affect is a clone of the original object.

  • That is exactly what I was looking for Thank You.



Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories