how to make a copy of object [VB] ?

W

wooz

There is a class (just simple example):

Public class clsTest
public x as integer
public y as integer
End class

There is an object:

dim obj as new clsTest
obj.x=5
obj.y=6

Now i want to make copy of object obj. I don't want to set each atribut in
new object one by one, like this:

dim obj2 as new clsTest
obj2.x=obj.x
obj2.y=obj.y

and i don't want to write a copy constructor for class clsTest:, so i write
a simple function:

public function CopyObj(byval argSourceObj as clsTest,byref argDestObj as
clsTes)
argDestObj=argSourceObj
end function

CopyObj(obj,obj2)

Unfortunetly it doesn't work. "Obj" and "Obj2" point to the same object.
Inside of function "CopyObj" there should be a copy of "Obj" becouse it is
passed by value not by reference. What do i wrong ? Is it possible at all to
make quick and easy copy of some objects ? Example above is very simple but
i use much more complex objects, so i'm looking for smart way to copy
objects.
 
D

Daniel Moth

You have to explicitly create your own copy constructor/method or worst do
the copying from the calling method (outside of the object). Serialization
could have helped you somewhat but it is not supported on CF (even there for
full control it is best implement iserializable rather than use the
attribute). You can pass structures by value hence creating a copy so you
could consider using them rather than classes but that would be a bit
drastic.

Cheers
Daniel
 
S

Sergey Bogdanov

You may consider shallow of your object through MemberwiseClone function
that is available as protected method. See this example:

Public Class clsTest
Public x As Integer
Public y As Integer

Public Function Copy() As clsTest
Return Me.MemberwiseClone()
End Function
End Class


Best regards,
Sergey Bogdanov
http://www.sergeybogdanov.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top