Compare String question: == or String.Compare?

  • Thread starter Thread starter Blue Ball
  • Start date Start date
B

Blue Ball

Is it always safe to use == to compare String?

e.g. if (my_str == "test") { }

or is it better to use: if (String.Compare(my_str, "test") == 0) { }

In old ASP, I remembered that there was slightly difference between the
operator compare and function compare. Can anyone confirm if I can use ==
safely?
 
Is it always safe to use == to compare String?

What do you mean by safe?

In old ASP, I remembered that there was slightly difference between the
operator compare and function compare. Can anyone confirm if I can use ==
safely?

Does different behaviour mean one is safe and the other is not?



Mattias
 
I mean Java, not old ASP. Everyone knows that it is not safe to use == to
compare String, because Java == compares the reference between the 2
variables, not the real content of the variables. Wondering if C# is acting
the same?
 
Blue Ball said:
I mean Java, not old ASP. Everyone knows that it is not safe to use == to
compare String, because Java == compares the reference between the 2
variables, not the real content of the variables. Wondering if C# is acting
the same?

No, C# will effectively call String.Equals, because the == operator is
overloaded. However, the type of both sides of the operator must be
string to do this - not just the runtime type, but the compile-time
type. Operators are overloaded at compile time, not runtime.
 
Blue said:
I mean Java, not old ASP. Everyone knows that it is not safe to use == to
compare String, because Java == compares the reference between the 2
variables, not the real content of the variables. Wondering if C# is acting
the same?

In C# the == operator for strings is overridden so it performs a
character-by-character 'ordinal' comparison, not a reference comparison.
It performs that same operation as the String.Equals() method.

However, that is still different from String.Compare(), which performs a
'culture-sensitive' comparison, so there will be times when a character
compares the same, but has a different binary representation. Depending
on your needs this might be exactly what you want - you'll have to study
the docs to see how exactly this might impact you.

 
Back
Top