Saturday, March 15, 2008

Comparing Objects (Pointer Equality) in VB.NET

It was not readily obvious to me how to compare references (pointers) to an object to see if both references are pointing to the same object in VB.NET.

The specific example that raised this question for me was the need to see if a reference pointing to a ToolStripMenuItem object was in a list of ToolStripMenuItem objects:

Private m_itemList As New Generic.List(Of ToolStripMenuItem)
.
.
.
Private Function GetItemPosition(ByVal item _
As ToolStripMenuItem) As Integer

For i As Integer = 0 To m_itemList.Count - 1

' If m_itemList(i)=item Then ' This doesn't work

If Object.ReferenceEquals(m_itemList(i), item) Then ' This does

Return i

End If

Next

Return -1
End Function


You can't just directly compare the references. You will get an error message that says: Operator '=' is not defined for types 'System.Windows.Forms.ToolStripMenuItem' and 'System.Windows.Forms.ToolStripMenuItem'. But there is a simple, if not readily obvious to me, solution. Just use the Object.ReferenceEqual method:

If Object.ReferenceEquals(item1, item2) Then
.
.
.
End If

3 comments:

Anonymous said...

Thanks for the post it helped me test some code that I'm working on right now.

ZEE said...

Thanks... that's not immediatly obvious... I was triing to obtain the pointers/references to compare with no success...

this way worked OK...

;-)

Anonymous said...

I suggest using the Is operator as in

If item1 Is item2 Then
...