tags:

views:

91

answers:

3
+2  Q: 

String Comparison?

Possible Duplicate:
Differences in string compare methods in C#

Is there any difference between these methods?

string.Compare(s1, s2) == 0
s1.CompareTo(s2) == 0
s1.Equals(s2)
s1 == s2

Which one should I use?

+2  A: 

refer this

Pramodh
Pramodh is right, search first before posting.
Martin Ongtangco
+1  A: 

From reflector:

public static int Compare(string strA, string strB)
{
    return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
}
public int CompareTo(string strB)
{
    if (strB == null)
    {
        return 1;
    }
    return CultureInfo.CurrentCulture.CompareInfo.Compare(this, strB, CompareOptions.None);
}

So CompareTo has an additional reference check than Compare.

public static bool operator ==(string a, string b)
{
    return Equals(a, b);
}

So == is exactly the same as Equals. The difference between two Compare and two Equals is, you can pass CompareOptions argument to Compare, and it returns 0/1/-1. while Equals doesn't receive a CompareOptions argument, and it can tell you TRUE/FALSE only.

Danny Chen
+1  A: 

there is an interesting post poseted by C# team member Kirill you may insterested

http://blogs.msdn.com/b/kirillosenkov/archive/2010/09/22/what-s-faster-string-equals-or-string-compare.aspx?

Hiber
Would be more interesting if they actually managed to answer the question ;)
Mark