Maha

Maha

  • NA
  • 0
  • 170.4k

sorting arrays of objects

Dec 17 2011 1:31 PM
Following program is all about sorting arrays of objects. It is comparing father's age and my age.

I couldn't understand what is Temp.Age. Anyone knows please explain.

using System;

public class Person : IComparable
{
public Person() { }
// private fields
private string _FirstName;
private string _LastName;
private int _Age;

public Person(string FirstName, string LastName, int Age)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
}
//Properties
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
//This was the interface member
public int CompareTo(object obj)
{
Person Temp = (Person)obj;

if (this.Age < Temp.Age)        //????????????????????????
{return 1;}

if (this.Age > Temp.Age)
{return -1;}
else
{return 0;}
}
}

//The method int CompareTo (object obj) returns an integer. You can specify your result according to the returned value as follow:

class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");

Person me = new Person("Bejaoui", "Bechir", 29);
Person myFather = new Person("Bejaoui", "Massinissa", 65);
Person myGrandFather = new Person("Krayem", "Shishaq", 95);

int state = me.CompareTo(myFather);

if (state == 1) Console.WriteLine("My father is older than me");
if (state == -1) Console.WriteLine("I'm older than my father!!!");
if (state == 0) Console.WriteLine("My Father and I have the same age!");

Console.Write("Press any key to continue . . . ");

Console.ReadKey(true);
}
}
/*
Hello World!
My father is older than me
*/

Answers (7)