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);
}
Loading
Posted Aug 25, 2012, 1:59 PM
VulpesPosted Aug 25, 2012, 1:35 PM
The others don't bother to check that the parameter passed does in fact refer to an Employee object and so will fail with the standard 'invalid cast exception' when the code is run if it refers to something else.
Even though the code is still throwing an exception, the programmer has control over what it's saying and it may be possible to catch it elsewhere in the call stack.
#2 also makes use of the existing Int32.CompareTo() method rather than coding this again from scratch.