0

This is my first question here, so when i do something wrong, pls be so kind and just say it. So. I have found this in a textbook. Its the Class of an Object Array Sort programm. It's exact the thing i need but it's really poorly explained in the book and i can't get clever out of it. So could someone maybe explain it detailed for me?This would really help me.

class Person : IComparable                     
{
    private string name;
    public Person()
    {
        name = "EMPTY";
    }
    public Person (string nm)
    {
        name = nm;
    }

    public string NAME
    {
        get
        {
            return name;
        }
    }
    public int CompareTo( object oneObject)   
    {
        Person comparePerson = (Person)oneObject;             
        return (name.CompareTo(comparePerson.name));    
    }
    public override string ToString()
    {
        return "Name of the Person: " + name;
    }}
  • 1
    I posted on here before asking for a section of code to be explained to me. The question was not well received. I have found, for this kind of question; ASP Forums is a good place to turn. https://forums.asp.net/ :-) – davvv Nov 19 '17 at 15:38
  • Thank you for your kindness :) – Sven Nov 19 '17 at 15:45
  • Stackoverflow is not the place for questions like this. Here we focus on finding solutions to specific problems, not on explaining code parts. – Zohar Peled Nov 19 '17 at 15:55

1 Answers1

0

This code is example for implementation of IComparable interface. You can use it in cases when you want use Sort() method on array, where instances is not values (classes, structs). This part of code describe sort principle for computer, how it should sort array of Person instances:

1.    public int CompareTo( object oneObject)   
2.        {
3.            Person comparePerson = (Person)oneObject;             
4.            return (name.CompareTo(comparePerson.name));    
5.        }

At line 3 Cast argument (it will be compared with current instance) to Person class. It's unsafe because you can get InvalidCastException if oneObject isn't Person class.

At line 4 comparing Name of current instanse with name of oneObject argument Properti Name is string. String has implementation of IComparable interface, and you use it.

When you call Sort() method on Array it will compare elemnts (using CopareTo(arg)) one-to-one, and arrange they based on results.

Anton Gorbunov
  • 1,414
  • 3
  • 16
  • 24