A
Author
I understand that if we wanna compare two objects of the same class,
we need to implement the IComparable interface, as shown here:
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto(printer).aspx
I am confused by the implementation of the CompareTo method in the C#
example on the above page. Look:
public int CompareTo(object obj)
{
if(obj is Temperature)
{
Temperature otherTemperature = (Temperature) obj;
return
this.temperatureF.CompareTo(otherTemperature.temperatureF);
}
else
{
throw new ArgumentException("object is not a Temperature");
}
}
The thing that baffles me is that the implementation of CompareTo
makes a call to this method itself. Hey, CompareTo is *not*
implemented in the interface (no interfaces implements a method), and
*we* are trying to implement it, then how are we able to call this
method in order to implement it? I don't understand the logic here.
Instead, I thought that the implementation of CompareTo in this case
should really be this:
public int CompareTo(object obj)
{
if(obj is Temperature)
{
Temperature otherTemperature = (Temperature) obj;
if (this.temperatureF < otherTemperature)
{ return -1; }
else if ((this.temperatureF == otherTemperature)
{ return 0; }
else
{ return 1; }
}
else
{
throw new ArgumentException("object is not a Temperature");
}
}
Dear gurus, so what is the reason behind calling CompareTo itself when
implementing it? Thank you.
we need to implement the IComparable interface, as shown here:
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto(printer).aspx
I am confused by the implementation of the CompareTo method in the C#
example on the above page. Look:
public int CompareTo(object obj)
{
if(obj is Temperature)
{
Temperature otherTemperature = (Temperature) obj;
return
this.temperatureF.CompareTo(otherTemperature.temperatureF);
}
else
{
throw new ArgumentException("object is not a Temperature");
}
}
The thing that baffles me is that the implementation of CompareTo
makes a call to this method itself. Hey, CompareTo is *not*
implemented in the interface (no interfaces implements a method), and
*we* are trying to implement it, then how are we able to call this
method in order to implement it? I don't understand the logic here.
Instead, I thought that the implementation of CompareTo in this case
should really be this:
public int CompareTo(object obj)
{
if(obj is Temperature)
{
Temperature otherTemperature = (Temperature) obj;
if (this.temperatureF < otherTemperature)
{ return -1; }
else if ((this.temperatureF == otherTemperature)
{ return 0; }
else
{ return 1; }
}
else
{
throw new ArgumentException("object is not a Temperature");
}
}
Dear gurus, so what is the reason behind calling CompareTo itself when
implementing it? Thank you.