Bubo
Bubo

Reputation: 808

Comparing Strings in .NET

I am running into what must be a HUGE misunderstanding...

I have an object with a string component ID, I am trying to compare this ID to a string in my code in the following way...

if(object.ID == "8jh0086s)
{
//Execute code
}

However, when debugging, I can see that ID is in fact "8jh0086s" but the code is not being executed. I have also tried the following

if(String.Compare(object.ID,"8jh0086s")==0)
{
//Execute code
}

as well as

if(object.ID.Equals("8jh0086s"))
{
//Execute code
}

And I still get nothing...however I do notice that when I am debugging the '0' in the string object.ID does not have a line through it, like the one in the compare string. But I don't know if that is affecting anything. It is not the letter 'o' or 'O', it's a zero but without a line through it.

Any ideas??

Upvotes: 2

Views: 182

Answers (3)

Timeout
Timeout

Reputation: 7909

I suspect there's something not easily apparent in one of your strings, like a non-printable character for example.

Trying running both strings through this to look at their actual byte values. Both arrays should contain the same numerical values.

var test1 = System.Text.Encoding.UTF8.GetBytes(object.ID);
var test2 = System.Text.Encoding.UTF8.GetBytes("8jh0086s");

==== Update from first comment ====

A very easy way to do this is to use the immediate window or watch statements to execute those statements and view the results without having to modify your code.

Upvotes: 3

user1618236
user1618236

Reputation:

Your first example should be correct. My guess is there is an un-rendered character present in the Object.ID.

You can inspect this further by debugging, copying both values into an editor like Notepad++ and turning on view all symbols.

Upvotes: 1

Moby Disk
Moby Disk

Reputation: 3851

I suspect you answered your own question. If one string has O and the other has 0, then they will compare differently. I have been in similar situations where strings seem the same but they really aren't. Worst-case, write a loop to compare each individual character one at a time and you might find some subtle difference like that.

Alternatively, if object.ID is not a string, but perhaps something of type "object" then look at this: http://blog.coverity.com/2014/01/13/inconsistent-equality

The example uses int, not string, but it can give you an idea of the complications with == when dealing with different objects. But I suspect this is not your problem since you explicitly called String.Compare. That was the right thing to do, and it tells you that the strings really are different!

Upvotes: 0

Related Questions