0

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
  • For the record: `Is` compares references, so your code attempts to check if `x` is the **exact** same object/instance as `y`. If you are merely looking to _**compare**_ the two then you should see this: https://stackoverflow.com/a/488301/3740093 - If the type you set as `T` is a _custom_ type you've got to make sure it overrides `Object.Equals()`, otherwise this won't work (pretty much all built-in .NET types does this, so you won't have to worry about them). – Visual Vincent Oct 24 '17 at 21:33

1 Answers1

1

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
NoAlias
  • 9,218
  • 2
  • 27
  • 46