Question Object Equality

njsokalski

Well-known member
Joined
Mar 16, 2011
Messages
102
Programming Experience
5-10
This is probably going to sound like a question from somebody who just started programming last week, but since I have never really needed the answer before, I never bothered to figure it out. I have a Do loop that I want to exit once it goes through without making any changes to an object I created. I figured the best way to do this was to create a temporary copy of the object at the beginning of the loop and then compare that to the actual object at the end of the loop to determine whether any changes were made to it. The problem occurs when variables are accessed and copied by reference. I have tried to use some of the methods such as .Clone and .Equals (maybe I shouldn't be using these, but I didn't see any better built-in methods), but I seem to be doing some stuff wrong. Can somebody give me an example of a good way to copy an object for later equality testing, and how to do the equality testing? Thanks.
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,412
Location
Norway
Programming Experience
10+
I don't think cloning and implementing value equality for a reference type is a good idea. Instead you should implement INotifyPropertyChanged Interface and use that to notify if the object state actually changes.

If you don't agree, why not override Equals to return True when you determine one object has same values as a different object?
 

njsokalski

Well-known member
Joined
Mar 16, 2011
Messages
102
Programming Experience
5-10
The objects I am testing for equality are an array of List(of x), a List(of x), and an array of a class I created. For the class I created, I have implemented the Equals method, so that takes care of that one, but what do I do for the List(of x) array and the List(of x)?
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,412
Location
Norway
Programming Experience
10+
What would make you say they are deemed the same? Same collection object? Different collection object containing same objects? Different collection object containing different objects that has same property values?
 

njsokalski

Well-known member
Joined
Mar 16, 2011
Messages
102
Programming Experience
5-10
All the properties in the classes I created are either Integers or arrays of Integers, so I want all of those properties to be equal (including the length of the arrays for the properties that are arrays of integers). The two Lists I am comparing are a List of Integers and an array of a List of Integers, so for them I simply need the lengths and integer values to be the same. The Lists are the place where I am really having the problems, because I need the temporary copy to not be modified between the beginning and end of the loop, but when they are copied by reference they get modified whenever I modify the original.
 
Top Bottom