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
VulpesPosted Aug 22, 2012, 6:08 PM
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.
Posted Aug 22, 2012, 6:19 PM
Posted Aug 22, 2012, 2:21 PM
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;
}
}
VulpesPosted Aug 22, 2012, 1:54 PM
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, 1:13 PM
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.
VulpesPosted Aug 22, 2012, 11:43 AM
Posted Aug 22, 2012, 6:33 AM
/*
Before Sort:
5, 4, 3, 2, 1,
After Sort:
1, 2, 3, 4, 5
*/
VulpesPosted Aug 22, 2012, 5:52 AM
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);