ProgLog
ProgLog

Reputation: 35

c# CompareTo() Method

I'm trying to understand CompareTo() in C# and the following example made me more confused than ever. Can someone help me understand why the result for the 3rd variation is 1? 2nd word in the sentence "Hello wordd" is not the same as str1 "Hello world" so why am I getting 1? Shouldn't I get -1?

static void Main(string[] args)
    {
        string str1 = "Hello world";
        Console.WriteLine(str1.CompareTo("Hello World"));
        Console.WriteLine(str1.CompareTo("Hello world"));
        Console.WriteLine(str1.CompareTo("Hello wordd"));

    }

Results: -1, 0, 1

Upvotes: 2

Views: 7809

Answers (2)

Rostam Bamasi
Rostam Bamasi

Reputation: 274

The String.CompareTo method compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes.

  • if the return value is Less than zero: This instance precedes value.

  • if the return value is Zero: This instance has the same position in the sort order as value.

  • if the return value is Greater than zero: This instance follows value. -or- value is null.

Upvotes: 6

Peter Dongan
Peter Dongan

Reputation: 2306

If the strings match, then CompareTo() gives 0. If they don't match, it gives a positive or negative number depending on which string comes first alphabetically.

In your example, both the results 1 and -1 indicate the strings do not match, while 0 indicates the strings match.

It looks like you are using it to determine equality and not to sort. If this is the case, then you should use Equals() instead.

Upvotes: 5

Related Questions