Home > Mobile >  String.Compare and how it actually function (IComparable implementation)
String.Compare and how it actually function (IComparable implementation)

Time:06-03

Well...I rewrote my post completely to allow anybody to understand what I am actually trying to understand. I just want to understand how String.Compare (string, string) actually function and understand which string precedes and which follows. MSDN describes it quite confusingly imo.Here is my code and it works correctly:

 internal class Animal: IComparable<Animal>
{
    public Animal(string name)
    {
        Name = name;
    }

    public string Name { get; private set; }

    static string[] animalsStringArray = { "Bull", "Frog", "Elephant", "Cat", "Dog", "Bird", "Horse" };
    public static Animal[] CreateAnimalsArray()
    {
        Animal[] animals = new Animal[animalsStringArray.Length];
        for (int i = 0; i< animalsStringArray.Length; i  )
        {
            animals[i] = new Animal(animalsStringArray[i]);
        }
        return animals;
    }
    public int CompareTo(Animal rightAnimal)
    {
        Animal leftAnimal = this;
        return String.Compare(leftAnimal.Name, rightAnimal.Name);
    }
    public override string ToString()
    {
        return Name;
    }
}

internal class Program
{
    public static void DisplayArray(IComparable<Animal>[] comp)
    {
        int num = 1;
        foreach (Animal s in comp)
        {
            Console.WriteLine("Name {0} is: {1}", num  , s.ToString());
        }
    }

    static void Main(string[] args)
    {
        Animal[] animals = Animal.CreateAnimalsArray();
        Console.WriteLine("\n\nHere is the animals array before being sorted out: ");
        DisplayArray(animals);
        Console.WriteLine("\n\nHere is the animals array after being sorted out: ");
        Array.Sort(animals);
        DisplayArray(animals);
        Console.WriteLine("\n\nPress Enter to terminate...");
        Console.ReadKey();
    }
}

And here is the actual output:

Here is the animals array before being sorted out:

Name 1 is: Bull

Name 2 is: Frog

Name 3 is: Elephant

Name 4 is: Cat

Name 5 is: Dog

Name 6 is: Bird

Name 7 is: Horse

Here is the animals array after being sorted out:

Name 1 is: Bird

Name 2 is: Bull

Name 3 is: Cat

Name 4 is: Dog

Name 5 is: Elephant

Name 6 is: Frog

Name 7 is: Horse

Press Enter to terminate...

BUT if I will switch position parameters for CompareTo() method in Animal class then the results will be absurd for some reason. Why? Here is what I meant by switching positions:

public int CompareTo(Animal rightAnimal)
    {
        Animal leftAnimal = this;
        return String.Compare(rightAnimal.Name, leftAnimal.Name);
    }

After these changes the output will be like this: Here is the animals array before being sorted out:

Name 1 is: Bull

Name 2 is: Frog

Name 3 is: Elephant

Name 4 is: Cat

Name 5 is: Dog

Name 6 is: Bird

Name 7 is: Horse

Here is the animals array after being sorted out:

Name 1 is: Horse

Name 2 is: Frog

Name 3 is: Elephant

Name 4 is: Dog

Name 5 is: Cat

Name 6 is: Bull

Name 7 is: Bird

Press Enter to terminate...

Some sort of a reverse order. But why? This guys (https://www.geeksforgeeks.org/how-to-compare-strings-in-c-sharp/) are using the word "lexicographically" (notice that they are not using the word alphabetically) but they don't decipher what it means. I understood it is like based on a culture. I feel that it is easy probably but I am so confused anyway.

CodePudding user response:

This has absolutely nothing to do with how String.Compare functions, except that it adheres to the same contract as CompareTo follows, and it is as follows:

String.Compare(a, b) returns negative number  --> a should come before b
String.Compare(a, b) returns positive number  --> b should come before a
String.Compare(a, b) returns zero             --> a and b are equivalent

(Usually, the numbers being returned are -1 or 1 for negative and positive respectively, but there's no requirement that only those values can be returned. For instance, if you're comparing numbers and don't need to consider under- or overflow, you can simply do a-b to get the difference, which will then map to negative or positive depending on which one is lower.)

The exact same behavior is expected from CompareTo:

a.CompareTo(b) returns negative number        --> a should come before b
a.CompareTo(b) returns positive number        --> b should come before a
a.CompareTo(b) returns zero                   --> a and b are equivalent

What you're observing is that reversing the parameters to the two methods will in fact return the opposite sign of value.

Example:

if String.Compare(a, b) returns a positive number, then String.Compare(b, a) should return a negative number

and vice versa

So basically, by reversing the order of parameters to String.Compare, you reverse the decision on which of the two should come first, and thus you get a reverse ordered result.

  • Related