Can I call the CompareTo() method required by the IComparable interface or is it only available to the System? In the following code, I can call the .Sort() method which uses the Icomparable<T>.CompareTo method that I wrote but I cannot call the .CompareTo method. Do I just have the wrong syntax?
When I try to type in the line to call .CompareTo, Visual Studio shows a red, squiggly line under CompareTo with this message:
"CS1061: 'Program.Person' does not contain a definition for 'CompareTo' and no accessible extension method 'CompareTo' accepting a first argument of type 'Program.Person' could be found"
class Program
{
public class Person : IComparable<Person>
{
public string sName;
public int iAge;
public Person(string name, int age)
{
this.sName = name;
this.iAge = age;
}
int IComparable<Person>.CompareTo(Person otherPerson)
{
// check if other person is a valid object reference
if (otherPerson == null)
{
if (this == null) return 0; // if both persons are null, return EQUAL
return 1; // if only other person is null, this person is greater
}
if (this == null) return -1; // if only this person is null, it is lesser
if (this.sName != otherPerson.sName) return String.Compare(this.sName, otherPerson.sName);
return this.iAge - otherPerson.iAge;
}
}
static void Main(string[] args)
{
List<Person> People = new List<Person>();
People.Add(new Person("Joe", 25));
People.Add(new Person("Clark", 36));
People.Add(new Person("Lois", 33));
// I can call the .Sort() method so the System can access my .CompareTo() method
People.Sort();
// Visual Studio does not accept this line. Error CS1061
if(People[0].CompareTo(People[1]) < 0)
{
// do something
}
Person Person1 = new Person("Bill", 28);
Person Person2 = new Person("Becky", 24);
// Visual Studio does not accept this line either. Error CS1061
if (Person1.CompareTo(Person2) < 0)
{
// do something
}
}