Search code examples
vb.netgenericsequality

Check Generic objects for equality in VB


It seems so trivial, yet I don't get it to work. I need to compare two generics of the same type T for equality:

Sub SomeMethod(Of T)(x As T, y As T) 
    If x Is y
        ' do stuff
    End If
End Sub

Compailer says no:

'Is' operand of type 'T' can be compared only to 'Nothing' because 'T' is a type parameter with no class constraint.


Solution

  • Give it a class constraint like this:

    Sub SomeMethod(Of T As Class)(x As T, y As T)
        If x Is y Then
            ' do stuff
        End If
    End Sub