Last Updated:

How to Compare Objects in C++ | .Net Framework

So, we've taken a closer look at copying objects. Now let's look at comparing objects. The .NET Framework uses the IComparable interface to compare objects. In this section, we'll use the IComparablé interface to sort an array as an example.

Array sorting

In the System::Array class, the static Sort method is used to sort the array. The ArrayName utility illustrates how to apply this method to sorting an array of Name objects, where the Name class contains just a string. Here is a listing of the main program:

//ArrayName.cpp
_gc class ArrayName
// garbage collector class ArrayName
{
public:
static void Main() {
Name *array[] = new Name*[5]; // Name
array[0] = new Name("Michael"); // new Name ("Michael")
array[1] = new Name("Charlie"); // new Name ("Charlie")
array[2] = new Name("Peter"); // new Name ("Peter")
array[3] = new Name("Dana"); // new Name ("Dana")
array[4] = new Name("Bob"); // new Name ("Bob")
if (dynamic_cast<IComparable *>(array[0])!= 0)
Array::Sort(array); else
Console::WriteLine(
"Name does not implement IComparable");
// (" Name (Name) does not implement IComparable");
lEnumerator *pEnum = array › GetEnumerator();
while (pEnum › MoveNext())
{
Name *pName = // Name
dynamic_cast<Name *>(pEnum › Current);
if (pName!=0)
Console::WriteLine(pName);
}
}
};

Implementing IComparable

In order to be able to perform sorting, it is necessary to define rules for comparing sorted objects. Such rules are implemented in the CompareTo method of the IComparable interface. Therefore, in order to be able to sort arrays containing data of the type you define, you must implement the IComparable interface for that data type.

_gc_interface IComparable
// garbage collector - IComparable
{
int CompareTo(Object*obj);
};

Here is a listing of the implementation of the Name class, including the implementation of the IComparable interface:

_gc class Name: public IComparable
{
private: // private
String *pText;
public:
Name(String *pText) // Name
{
this › pText = pText;
}
_property String* get_Item()
{
return pText;
}
_property void set_Itern(String*pText)
{
this › pText = pText;
}
int CompareTo(Object *pOb]) // Object
{
String *pSl = this › pText;
String *pS2 =
(dynamic_cast<Name *>(pObj)) › pText;
return String::Compare(pSl, pS2); // compare names
}
String *ToString()
{
return pText;
}
};

The result of the program is an alphabetically ordered list of names:

Bob // Bob
Charlie // Charlie
Dana // Dana
Michael // Michael
Peter // Peter