Overloading Equals with specific types -- not being used by Hashtable?

parsifal

New member
Joined
Aug 30, 2007
Messages
3
Programming Experience
10+
Hi,

I have the following code defined:

VB.NET:
Public Overloads Function Equals(ByVal other as MyClass) As Boolean
	Return Id = other.Id
End Function

However, when I use the ContainsKey method of Hashtable, my Equals function never gets called. Is there something I'm missing?
 
Last edited:
I should add that when I do the following (see code below), it works. But I shouldn't have to do it this way; I shouldn't have to use Overrides, and check the type myself.

VB.NET:
Public Overrides Function Equals(ByVal obj As Object) As Boolean
	If obj.GetType Is GetType(MyClass) Then
		Dim other As MyClass = obj

		Return other.Id = Id
	Else
		Return MyBase.Equals(obj)
	End If
End Function
 
Last edited:
You need to Overrides; if you use overloads, then VB will look at the boxing of the parent and/or argument when determining which to call

Becuase hashtable is full of Object, it is Object.Equals(other Object) that gets called. If you Overloads, you add a method, but the hashtable is still going to pick the original because it is still comparing object.. Yes we know that your MyClass is the boxed type, but vb assesses which to call by looking at the box type, not the boxed type

VB.NET:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal ea As System.EventArgs) Handles MyBase.Load

        Dim e As New Eg
        
        Dim oe As Object = e
        
        e.Equals(oe)
        oe.Equals(e)
        e.Equals(e)
        oe.Equals(oe)
    End Sub
End Class

Class Eg

    Overloads Function Equals(ByVal ex As Eg) As Boolean
        MessageBox.Show("My overloads was called")
        Return False

    End Function

    Overrides Function Equals(ByVal ex As Object) As Boolean
        MessageBox.Show("My overrides was called")
        Return False

    End Function




End Class

The ONLY time overloads will be called is in e.Equals(e) - i.e. the box is Eg and the argument box is Eg. FOr all other cases where a Object box is involved, overrides is called. Hashtable uses object, Overrides is needed
 
Back
Top