Class1 = Class2 I want an actual copy

kevinheeney

Newcomer
Joined
Jun 24, 2003
Messages
20
VB.NET

Hello,
I am having a problem with copying one class into another. In the following example (a much more detailed example is attached) 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.

Kevin
 

Attachments

Last edited:
here's a sample class i knocked up ...
Visual Basic:
Public Class Class1
    Public intValue As Integer = 0

    Public Sub setValue(ByVal x As Integer)
        intValue = x
    End Sub

    Public Sub CheckValue()
        MessageBox.Show(intValue.ToString())
    End Sub

End Class
then in your form....
Visual Basic:
    Private cls1 As New Class1() '/// make this one new.
    Private cls2 As Class1 '/// but not this one.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        cls1.setValue(1500)
        cls2 = DirectCast(cls1, Class1) '/// cls2 is now a copy of cls1
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If Not cls2 Is Nothing Then
            cls2.CheckValue()
        End If
    End Sub
 
Clone

I think you are looking for the MemberwiseClone() function that creates a shallow copy of the current object. See MSDN for the method System.Object.MemberwiseClone()
 
You could overload the constructor of your class to create a copy-constructor. It would take an object of the same type as parameter and then copy the state of the object passed to the newly created object.

Visual Basic:
Public Class cl1

    Public Sub New()
    End Sub

    Public Sub New(ByVal first As Integer, ByVal second As Integer)
        Me.someValue1 = first
        Me.someValue2 = second
    End Sub

    'The Copy-constructor
    Public Sub New(ByVal toCopy As cl1)
        Me.someValue1 = toCopy.someValue1
        Me.someValue2 = toCopy.someValue2
    End Sub

    Public Overrides Function ToString() As String
        Return "(" + Me.someValue1.ToString() + "," + Me.someValue2.ToString() + ")"
    End Function

    Private someValue1 As Integer
    Private someValue2 As Integer

End Class

Public Class Tester

    Public Shared Sub Main()
        Dim obj1 = New cl1(2, 3)
        Dim obj2
        obj2 = New cl1(obj1)

        Console.WriteLine(obj1.ToString())
        Console.WriteLine(obj2.ToString())

    End Sub

End Class
 
Back
Top