Confused by the CompareTo method of IComparable

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.
 
J

Jon Skeet [C# MVP]

Author said:
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.

Where? It looks to me like it's calling double's implementation of
CompareTo.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top