Help with classes

J

Jared

Hi,

Problem is when I update a copy of a object variable it updates the object
variable it was copied from. see code below..

Sub Main()
Dim cat1 As New cat
Dim cat2 As cat
cat1.Color = ConsoleColor.Black
cat2 = cat1
cat2.Color = ConsoleColor.Blue
Trace.WriteLine(cat1.Color.ToString)
End Sub


Public Class cat
Dim mColor As ConsoleColor
Public Property Color() As ConsoleColor
Get
Return mColor
End Get
Set(ByVal value As ConsoleColor)
mColor = value
End Set
End Property
End Class

All the dam cats are now blue!!! I only want cat 2 to be blue.

TIA
Jared
 
P

PvdG42

Jared said:
Hi,

Problem is when I update a copy of a object variable it updates the object
variable it was copied from. see code below..

Sub Main()
Dim cat1 As New cat
Dim cat2 As cat
cat1.Color = ConsoleColor.Black
cat2 = cat1
<snip>

Right here. cat2 = cat1
You are dealing with object variables, which are reference types (i.e. they
hold the address of the actual object).
The assignment statement stores the *address* of the object referenced by
cat1 in cat2, thus making cat2 a second reference to the same object.
There is no second object.
 
M

Mr. Arnold

Jared said:
TY, is there a easy workaround?

Dim cat1 as new cat // It is its own cat. It is its own object
Dim cat2 As new cat // It is its own cat. It is its own object

You deal with each cat/object separately. And you don't cat2 = cat1.

Your way of

Dim cat1 as new cat ' Cat1 is its own cat. It is its own object.
dim cat2 as cat ' Cat2 is not its own cat. It was not born with
the (new) keyword.
' Cat2 only has
characteristics/properties of being a (cat).

and then setting cat2 = cat1 set reference to cat1 they are the same cat at
that point.

You do something to cat2, you're doing it to cat1. You use cat2, you're just
getting cat1, because the pointer for cat2 is pointing to cat1. Cat1 is the
only cat that's there and alive.
 
J

Jack Jackson

TY, is there a easy workaround?

If your class is really as simple as your example, you could add a
constructor that takes a reference to an existing instance and sets
the properties of the new instance look like the existing instance:

Sub Main()
Dim cat1 As New cat
Dim cat2 As cat
cat1.Color = ConsoleColor.Black
cat2 = New cat(cat1)
cat2.Color = ConsoleColor.Blue
Trace.WriteLine(cat1.Color.ToString)
End Sub


Public Class cat
Dim mColor As ConsoleColor
Public Property Color() As ConsoleColor
Get
Return mColor
End Get
Set(ByVal value As ConsoleColor)
mColor = value
End Set
End Property

Sub New(_cat as cat)
Me.Color = _cat.Color
End Sub

End Class
 

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