2

Is Operator works fine when comparing two strings like:

Dim str1 As String = "TagnameX"
Dim str2 As String = "TagnameX"

Dim strChk as boolean = str1 Is str2
'strChk returns True

But when one of the strings is extracted by Substring it returns false ! as below:

Dim str1 As String = "t#1TagnameX"
Dim str1Extract As String = str1.Substring(3, 8)
Dim strArr() = {"Tagname1", "Tagname2", "TagnameX"}  

 For i = 0 To strArr.Length - 1
      If strArr(i) Is str1Extract Then
         MsgBox("TagnameX found!")
      else
         MsgBox("TagnameX was not found!")
      End If
 Next
'TagnameX was not found!

so am i using it wrong in some how? thanks for your help! :)

2 Answers2

6

The Is-operator returns whether two references are equal: that is, whether the two variables refer to the same location in memory.

The first code snippet returns True because for literal strings, .NET interns duplicates rather than keeping separate identical copies in memory, so str1 and str2 refer to the same string in memory.

The second code snippet returns False because .NET does not necessarily intern intermediate strings, such as strings returned by Substring. So the variables str and strExtract do not refer to the same string.

You should use the equals operator = to compare the value of two strings.

pmcoltrane
  • 3,052
  • 1
  • 24
  • 30
3

I don't think that the Is operator does what you think it does.

The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.

https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/is-operator

Instead just use = to compare string values.

If strArr(i) = str1Extract Then
Philipp Grathwohl
  • 2,726
  • 3
  • 27
  • 38
  • Although what you said normally makes sense, the `String` `Is` operator has been redefined to compare values, so OP's example makes sense. The redefinition probably just doesn't hold in some specific cases. – laancelot Feb 17 '20 at 20:14
  • @laancelot interesting. The docs didn't mention specific behaviour for strings. Do you have some resource about that? – Philipp Grathwohl Feb 18 '20 at 07:59
  • @PhilippGrathwohl I should have linked it while I had it, and I can't put my hand on it today. I'll update you if I find it again. – laancelot Feb 18 '20 at 12:59
  • @PhilippGrathwohl Still can't find my source, but nevermind anyway. Experimenting showed that the `Is` _does_ compare references. At initialization, string variables with the same value will point toward the same memory cells. [You can "fool" the compiler by concatenating strings and avoid this comportment](https://dotnetfiddle.net/B10ox9). I admit I prefer this to the alternative. – laancelot Feb 18 '20 at 14:12