Object reference and cloning

kpgraci

Active member
Joined
Feb 21, 2011
Messages
30
Location
New Orleans
Programming Experience
10+
I have a form that accepts a byval client object in the New

VB.NET:
private _client as clsClient = Nothing
Public Sub New(ByVal client As clsClient)
    InitializeComponent()
    _client = client
End Sub

I call this from another form like this:

VB.NET:
Dim f As New frmEditClient(_client)
If f.ShowDialog() = DialogResult.OK Then
    _client = f.Client
End If

clsClient implements INotifyPropertyChanged

On the calling form I have labels bound to the properties of the _client object, like first and last name.

On frmEditClient if have textboxes bound to the same fields

What is happening that I don't understand is that when I'm showing the frmEditClient as a modal window of the calling form, when I change
the first name, for example, the labels bound to those fields on the calling form are also changed as I type, indicating that they both point to the same object.

Now this is rather cool, but I expected the object to copied and a new instance to exist in the frmClient modal form, but obviously it is the same instance.
Is this because the object is a reference type and so by specifying byval in the frmEditClient creator has the same effect as passing byref?

I wanted a separate object in case the user edited the object in frmEditClient and then decided to hit the cancel button and not commit the changes. In this case, do I need to clone the client object before I send it to the frmEditClient?

Like this:

VB.NET:
dim _cloneOfClient as clsClient = _client.Clone
Dim f As New frmEditClient(_cloneOfClient)
If f.ShowDialog() - DialogResult.OK Then
    _client = f.Client
End If

Problem: There is no clone method. How do I get a copy of an object that is a new object?

Or is there a better way to do what I'm trying to do?

thx
 
In an attempt to resolve this I implemented IClonable in my class clsClient:

VB.NET:
Implements ICloneable
Public Function Clone() As Object Implements System.ICloneable.Clone
    Return MyBase.MemberwiseClone()
End Function

Then I do this to an exisiing client object:

VB.NET:
Dim _clientClone As clsClient = _client.Clone

Problem:

_clientClone should be a new instance (shallow clone), but when I change the proerties of _clientClone ,_client also changes!

Why would that be?
 
Resolved

VB.NET:
If f.ShowDialog() - DialogResult.OK Then
    _client = f.Client
End If

should be:

VB.NET:
If f.ShowDialog() = DialogResult.OK Then
    _client = f.Client
End If

= sign in compare instead of -, stupid typo, object was always assigned, lol


I do however still need a memberwise copy of the fileds of one object into another, because the line:

VB.NET:
_client = _clientClone

Does not update the data bindings on the current form, but:

VB.NET:
_client.First = _clientClone.first

works fine, so if I had a memerwise copy of all properties I'd be set.

thx for listening...
 
Last edited:
Back
Top