Continuing in my develpment of C# and .Net I am struggling to understand the purpose of interfaces but particularly the IComparable interface. If the interface is implemented it provides a comparison method but what advantage does this provide over the comparison methods String.CompareTo or Int32.CompareTo. These can be called without implementing IComparable. Can someone explain? Have searched internet and not found a useful explanation.
tx
Loading

Suthish NairRank #92 · 22.8K reputationPosted Feb 13, 2011, 7:03 AM EST
Sam HobbsRank #107 · 20.5K reputationPosted Feb 13, 2011, 4:38 PM EST
Amit ChoudharyRank #145 · 15.8K reputationPosted Feb 13, 2011, 7:04 PM EST
"String.CompareTo or Int32.CompareTo. These can be called without implementing IComparable. "
Yes these can be called directly because Class String and Int32 already implemented the IComparable interface.
if you want your class say.. TestClass and you want to provide the action to comapre objects then you can not directly call the CompareTo method with you custom class object.
Implement the IComparable interface the you are good to go. you'll be able to write TestClass.CompareTo() as we do using inbuilt classes.
Thanks..
Darren Murray11 reputationPosted Feb 14, 2011, 2:31 PM EST
http://www.c-sharpcorner.com/UploadFile/prasadh/IComparablePSD12062005010125AM/IComparablePSD.aspx
My understanding is the Array.Sort(employees) invokes the CompareTo method in the Employee class. But how/why? Also in the CompareTo method the method is comparing this.Id and temp.Id. I am not understanding where each value is coming from (what is being passed to the method to create the temp instance?)
Amit ChoudharyRank #145 · 15.8K reputationPosted Feb 14, 2011, 7:29 PM EST
Ans to WHY? : they are comparing two objects of class Employee based on the EmpID attribute.
Ans to How?: By writing the logic in override of CompareTo method of IComparable interface.
Ans to "what is being passed to the method to create the temp instance?":
The object need to be compared is passed in CompareTo as an argument and then explicitly converting it to Employee class type. Look at it:
public int CompareTo(object obj)
{
Employee temp=(Employee)obj;
.....
}
Hope you got all your answers and might clearing your doubts.
Please mark "Do you like this post?" if it really helped you.
Darren Murray11 reputationPosted Feb 15, 2011, 4:00 PM EST
Amit ChoudharyRank #145 · 15.8K reputationPosted Feb 15, 2011, 6:47 PM EST
Thanks.. :)