Mohammed Almudhafar
Mohammed Almudhafar

Reputation: 67

Comparing strings in a loop using Is Operator

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! :)

Upvotes: 2

Views: 485

Answers (2)

Philipp Grathwohl
Philipp Grathwohl

Reputation: 2836

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

Upvotes: 3

pmcoltrane
pmcoltrane

Reputation: 3112

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.

Upvotes: 6

Related Questions