2
Answers

Different ways in implementing CompareTo()

Ask a question
Maha

Maha

12y
867
1
Following are the three different ways of implementing CompareTo(). Could you tell me please which is the most acceptable to programmers and why?

1)
public int CompareTo(Object o)
{
int returnVal;

Employee temp = (Employee)o;

if (this.idNumber > temp.idNumber)
returnVal = 1;
else
if (this.idNumber < temp.idNumber)
returnVal = -1;
else
returnVal = 0;

return returnVal;
}

2)
public int CompareTo(Object o)
{
if (o is Employee)
{
Employee temp = (Employee)o;
return temp.idNumber.CompareTo(this.idNumber);
}
else
throw new ArgumentException("Object is not a Employee.");
}

3)
public int CompareTo(Object o)
{
Employee temp = (Employee)o;
return (this.idNumber - temp.idNumber);
}


Answers (2)