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
Amit ChoudharyPosted Feb 15, 2011, 11:47 PM
Thanks.. :)
Darren MurrayPosted Feb 15, 2011, 9:00 PM
Amit ChoudharyPosted Feb 15, 2011, 12:29 AM
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 MurrayPosted Feb 14, 2011, 7:31 PM
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 ChoudharyPosted Feb 14, 2011, 12:04 AM
"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..
Sam HobbsPosted Feb 13, 2011, 9:38 PM
Suthish NairPosted Feb 13, 2011, 12:03 PM