8
Answers

IComparable

Ask a question
Maha

Maha

12y
972
1
Program in the following website is altered (http://www.c-sharpcorner.com/UploadFile/prasadh/IComparablePSD12062005010125AM/IComparablePSD.aspx)

Whether it is < or > output is same. Please explain the reason. Problem is highlighted.

using System;
class Employee : IComparable
{
private int Id;

public Employee(int id)
{
this.Id = id;

}
public int CompareTo(object obj)
{
Employee temp = (Employee)obj;

if (this.Id < temp.Id) //if(this.Id>temp.Id)
return 1;
else
if (temp.Id == this.Id)
return 0;
else
return -1;

}
public static void Main()
{
Employee[] employees = new Employee[5];

Console.WriteLine("Before Sort:");
for (int i = 0; i < employees.Length; i++)
{
employees[i] = new Employee(5 - i);
Console.Write("{0}, ", 5-i);
}
Console.WriteLine("\n");

Array.Sort(employees);
Console.WriteLine("After Sort:");
for (int i = 0; i < employees.Length; i++)
{
Console.Write("{0}, ", 5 - i);
}
Console.WriteLine();
Console.ReadKey();
}
}

/*
Before Sort:
5, 4, 3, 2, 1,

After Sort:
5, 4, 3, 2, 1,
*/


Answers (8)