Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings in a loop using Is Operator

Tags:

vb.net

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

like image 747
Mohammed Almudhafar Avatar asked Nov 30 '25 16:11

Mohammed Almudhafar


2 Answers

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.

like image 79
pmcoltrane Avatar answered Dec 02 '25 20:12

pmcoltrane


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
like image 36
Philipp Grathwohl Avatar answered Dec 02 '25 18:12

Philipp Grathwohl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!