This program is altered for simplicity. For example data given to ID 100, 200 and 300. Return will be 1, -1 or 0. this.ID can take 100, 200 or 300. What value tem.ID can take. Problem is highlighted.
using System;
namespace ConsoleApplication1
{
class StudetCompare
{
static void Main(string[] args)
{
int x;
Student[] student = new Student[3];
for (x = 0; x < student.Length; ++x)
{
student[x] = new Student();
Console.Write("Student #{0} ID = ", x + 1);
student[x].ID = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
Array.Sort(student);
for (x = 0; x < student.Length; ++x)
{
Console.WriteLine("Student #{0} ID = {1}", x + 1, student[x].ID);
}
Console.ReadKey();
}
}
class Student : IComparable
{
public int ID { get; set; }
public int CompareTo(object student)
{
Student tem = (Student)student; //Note: IComparable is non generic therefore casting
return (this.ID - tem.ID);
}
}
}
/*
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
Student #1 ID = 100
Student #2 ID = 200
Student #3 ID = 300
*/