Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: What is the difference between CompareTo(String) and Equals(String)? [duplicate]

Tags:

string

c#

I would like to know, when comparing string in C#? which method is suitable to use and why?

CompareTo() or Equals()?

like image 812
TheOneTeam Avatar asked Feb 01 '12 01:02

TheOneTeam


4 Answers

From MSDN:

string.CompareTo:

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.

string.Equals:

Determines whether two String objects have the same value.

In short, CompareTo is used for sorting. Equals is used to determine equality.

like image 108
ken Avatar answered Oct 08 '22 18:10

ken


CompareTo() tells you which, and if, one is greater/less than the other, while Equals() simply tells you if they are equivalent values.

If all you want to know is "are they the same values", you use Equals(). If you need to also know how they compare, use CompareTo()

int a = 50;
int b = 10;

//if you need to know if they are equal:
if(a.Equals(b)){
    //won't execute
}

//this would check if they are equal, as well
if(a.CompareTo(b) == 0){
    //won't execute
}

//if you need to know if a is bigger than b, specifically:
if(a.CompareTo(b) > 0){
    //will execute
}

//this would check to see if a is less than b
if(a.CompareTo(b) < 0){
    //won't execute
}

Finally, note that these Equals() and CompareTo() methods are not strictly needed for primitive types like int, because the standard comparison operators are overloaded, so you could do these:

//this would check if they are equal, as well
if(a == b){
    //won't execute
}

//if you need to know if a is bigger than b, specifically:
if(a > b){
    //will execute
}

//this would check to see if a is less than b
if(a < b){
    //won't execute
}

Finally, you mentioned string in your question. Equals() and CompareTo() work as I have describe for string as well. Just keep in mind the 'comparison' that CompareTo() does on strings is based on alphabetical sorting, so "abcdefg" < "z"

like image 26
Andrew Barber Avatar answered Oct 08 '22 19:10

Andrew Barber


The functionality in CompareTo is actually a superset of functionality of Equals. A CompareTo function dictates ordering, before, after or equals while the Equals function merely dictates equality. Hence it's actually possible to define Equals in terms of CompareTo

public bool Equals(string other) {
  return 0 == CompareTo(other);
}
like image 6
JaredPar Avatar answered Oct 08 '22 19:10

JaredPar


Equals will return a boolean for equality.

CompareTo will return an int, with -1 (or any other negative value) for "less than", 0 for "equals", or 1 (or any other positive value) for "greater than". This method is useful for sorting algorithms.

like image 5
ziesemer Avatar answered Oct 08 '22 19:10

ziesemer