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,
*/
Loading

VulpesRank #55 · 29.2K reputationPosted Aug 22, 2012, 2:08 PM EDT
All the code is in the same class and so the static Main method can access the private instance field idNumber of the myAssistant object.
VulpesRank #55 · 29.2K reputationPosted Aug 22, 2012, 1:52 AM EDT
It's printing the numbers 5 to 1 in decreasing order using this line where i ranges from 0 to 4:
Console.Write("{0}, ", 5 - i);
Posted Aug 22, 2012, 2:33 AM EDT
/*
Before Sort:
5, 4, 3, 2, 1,
After Sort:
1, 2, 3, 4, 5
*/
VulpesRank #55 · 29.2K reputationPosted Aug 22, 2012, 7:43 AM EDT
Posted Aug 22, 2012, 9:13 AM EDT
I couldn't understand
Console.Write("{0}, ", employees[i].Id);
Because object.method is in get and set method or object.instanceVariable in automatic properties are familiar with. But here object.instanceVariable is coming again. Is there any additional explanation for that.
VulpesRank #55 · 29.2K reputationPosted Aug 22, 2012, 9:54 AM EDT
We're able to access this private field here because all the code, including the Main() method, is within the Employee class itself - we don't need to expose it via a public property.
Posted Aug 22, 2012, 10:21 AM EDT
using System;
public class CreateEmployee
{
public static void Main()
{
Employee myAssistant = new Employee(123);
Console.WriteLine("ID # is {0}", myAssistant.idNumber);
Console.ReadKey();
}
private int idNumber;
public Employee(int idNumber)
{
this.idNumber = idNumber;
}
}
Posted Aug 22, 2012, 2:19 PM EDT