Wompguinea
Wompguinea

Reputation: 378

String.compare returns true when strings aren't equal?

I've seen plenty of questions here about strings that are equal returning as unequal, but trust me to not get that problem.

I have this function.

Protected Sub ChkValidStockCode()
    If Not (Voucher.ValidStockCode = "") Then
        Dim validcount As Int32 = 0
        Dim validproduct As String = Product.GetProductNameByCode(Voucher.ValidStockCode)
        For Each rpi As RepeaterItem In rptCart.Items
            Dim ProductID As HyperLink = CType(rpi.FindControl("hlProductID"), HyperLink)
            Dim ProductName As HyperLink = CType(rpi.FindControl("hlProductName"), HyperLink)
            If (String.Compare(Voucher.ValidStockCode.ToString(), ProductID.ToString())) Then
                validcount = validcount + 1
            End If
        Next

        If validcount = 0 Then
            txtVoucher.Text = "Sorry, this voucher is only valid when purchasing a " & validproduct
            failed = True
            Exit Sub
        End If
    End If

End Sub

It's supposed to compare the two strings and increment a validcount integer if they're equal, and then tell you off if it gets to the end of the repeater without finding any matches.

The variables in this test are LT00004 (Voucher.ValidStockCode) and SP08076 (ProductID.ToString())

I have run the code several times, outputting the different strings as the result and can confirm they are what they should be, but when I try to compare them (and I expect validCount to be 0), they return as a match.

What did I do to screw this up?

Upvotes: 0

Views: 189

Answers (1)

jimSampica
jimSampica

Reputation: 12420

You probably want String.Equals() and not String.Compare(). Compare is used to order things and not test for equality. What's happening is String.Compare is returning a non-zero number so the condition is being satisfied. The reason for that is because in VB "0" is False but any non-zero number evaluates to true. There's a whole history behind why that's the case but I digress.

Upvotes: 4

Related Questions