serhio
serhio

Reputation: 28586

String comparison in .NET

What is the difference (in bref) between (.NET)

myString == otherString

and

myString.CompareTo(otherString) == 0

Upvotes: 3

Views: 4054

Answers (6)

Diego
Diego

Reputation: 18349

There's no difference, except when myString is null, in which case myString.CompareTo(otherString) throws an error (NullReferenceException). Also, using CompareTo is a little bit slower than ==.

Only use CompareTo when you are interested in knowing if a string is before or after another one in an alphabetical sorting of them. For example "Car".CompareTo("Cat") returns -1 because "Car" is before "Cat" when ordered alphabetically.

Upvotes: 8

Alex
Alex

Reputation: 6149

The myString.CompareTo(otherString) method main purpose is to be used with sorting or alphabetizing operations. It should not be used when the main purpose is to check the equality of strings.

To determine whether two strings are equivalent, call the Equals method."

It's better to use .Equals instead of .CompareTo when looking solely for equality. since I also think it is faster for the compiler than the == operation.

Upvotes: 0

N_A
N_A

Reputation: 19897

From here:

The CompareTo method was designed primarily for use in sorting or alphabetizing operations. It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. To determine whether two strings are equivalent, call the Equals method.

The Equals method is more appropriate. From here, the difference between Equals and == is that Equals requires its parameter to be non-null and == does not. Plus, == is implemented to use Equals so Equals will always have better performance.

Upvotes: 1

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239636

CompareTo should only be used for assessing ordering. It may be that, for whatever reason, two strings compare the same for ordering purposes, but should not be considered equal (that is, == and Equals may return false).

To quote the documentation:

Compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String.

Emphasis added - note that it does not say that the two objects are equal.

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20620

Assuming you meant == and not =

CompareTo implements the IComparable interface. It returns an integer.

Upvotes: 1

Eugen Rieck
Eugen Rieck

Reputation: 65244

Assuming that you meant

myString == otherString

there is no visible difference.

Upvotes: 1

Related Questions