1

I need to compare two objects of the same class by value to see whether all their values match or not.

For background this is so I can compare before and after values of a wpf datagrid row

Say the objects are both House class with properties of name, street, town (all strings).

So the class would be

public class House
  public property name as string
  public property street as string
  public property town as string
end class

Should I

1) override equals in the House class and in it check name=name, street=street, town=town

2) make the House class implement IComparable and create a compare function that implements it, checking each property as 1

3) there's a better way you know that I dont!

I'd appreciate an example based on this scenario if possible.

Many thanks

user3844416
  • 125
  • 7

1 Answers1

1

You should be using Option 1 : Overriding the Equals method.

Why ?

Because the Equals() method is supposed to be used when you want to compare if two objects are the same.

So what's the use of IComparabe ?

IComparable interface has a different purpose. Its goal is to check if an object is supposed to go before or after another object. Therefore this is used by sorting methods.

You can implement the IComparable interface and check if two object's CompareTo() method return 0. However it only means that they are supposed to get the same ranking, not that they are equals...

Is there another approach ?

There are plenty differents ways of doing what you want to do. But since there is a simple and elegant method that is here, let's use that one. The main difficulty in programming an application is to find the tools that are already here to do what you want...

So how to Override the Equals() method ?

This link to MSDN explains how to override the Equals method

In short (I'm just copy/pasting from MSDN and removing error checking for clarity here) :

Public Class Point  
    Protected x As Integer
    Protected y As Integer

    Public Sub New (xValue As Integer, yValue As Integer)
     Me.x = xValue
     Me.y = yValue
    End Sub

    Public Overrides Overloads Function Equals(obj As Object) As Boolean
       Dim p As Point = CType(obj, Point)
       Return Me.x = p.x And Me.y = p.y
    End Function 
End Class 

Do not use this straight ahead and read article first, as you must do some error checking in the Equals, because it could throw some exception when converting Object to Point...

Martin Verjans
  • 4,675
  • 1
  • 21
  • 48