Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

C# Objects and the IComparable Interface

 

All C# classes, including arrays, are ultimately derived from the base class called object. The object keyword is an alias for the class System.Object. The following code fragment identifies some of the methods defined in the System.Object classgif:

namespace System
{
    public class Object
    {
	public Object() { ... }
	public virtual bool Equals(object o) { ... }
	public virtual int GetHashCode() { ... }
	public Type GetType() { ... }
	public virtual string ToString() { ... }
	// ...
    }
}

Notice that the C# System.Object class contains a method called Equals, the purpose of which is to indicate whether some other object is ``equal to'' this one. By default, obj1.Equals(obj2) returns true only if obj1 and obj2 refer to the same object.

Of course, any derived class can override the Equals method to do the comparison in a way that is appropriate to that class. For example, the Equals method is overridden in the System.Int32 class as follows: If obj1 and obj2 are Int32s, then obj1.equals(obj2) is true when (int)obj1 is equal to (int)obj2.

So, all C# objects provide a means to test for equality. Unfortunately, they do not provide a means to test whether one object is ``less than'' or ``greater than'' another. To overcome this difficulty, C# provides the standard interface called IComparable . The following code fragment defines the IComparable interface.

namespace System.Collections
{
    public interface IComparable
    {
	int CompareTo(object o);
    }
}

The IComparable interface defines a single method. This instance method takes a specified object and compares it with the given object instance. The method returns an integer that is less than, equal to, or greater than zero depending on whether this object instance is less than, equal to, or greater than the specified object instance o, respectively.




next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.