Base Data Types
  Sort an array
  Format a string
  Parse datatypes
  Compare references
  Compare object values
  Use mathematical functions

Get URL for this page

How Do I...Compare the value of two objects?

This sample illustrates how to compare any two values by using the IComparable interface that all the base types implement. The Max method shown below returns the maximum of any two values that implement IComparable. The CompareTo method on IComparable has the following return values: < 0 if the value is less than the current instance, == 0 (= 0 in VB) if the value is equal to the current instance, or > 0 if value is greater than the current instance. A custom implementation of IComparable is also shown.

 
VB Compare.aspx

[Run Sample] | [View Source]

To compare two objects to each other, they should implement the IComparable interface. This interface has a CompareTo method that allows you to compare one object to another and determine if one object is less than, greater than, or equal to another object. For the moment, assume you are dealing with string or numeric data, where the rules are already known.

The base data types all support the IComparable interface, which means they can all be compared to one another. The following code example demonstrates a fairly simple routine called Max, which accepts two objects, both of which support IComparable. Using the CompareTo method of those objects, you will do some standard comparisons to determine which one is the greater of the two (which is then returned out of the method). While what you pass into this routine are the objects you want to compare, inside the routine you only deal with the IComparable nature of those objects, which is why the data type of the return value and the parameters is IComparable, not Object. If you try to use this particular routine with objects that do not support IComparable, you will get a compile error.


Public Shared Function Max (val1 As IComparable , _
			val2 As IComparable) As IComparable

	If (val1.CompareTo(val2) > 0)
		Return val1  '  val1 > val2
        End If

	If (val1.CompareTo(val2) < 0)
		Return val2  '  val1 < val2
	End If

	If (val1.CompareTo(val2) = 0)
		Return val1  '  val1 = val2, return val1
	End If
End Function
VB

To use the above example, you can pass into the Max routine any two objects that support IComparable. You can flow through the Max routine yourself to determine which object will be passed back as the 'max'. Remember that the nature of how these objects are compared is defined within the objects themselves.


Console.WriteLine ( Max (5, 10) )             '  comparing integers
Console.WriteLine ( Max (4.3, 2.5) )          '  comparing doubles
Console.WriteLine ( Max ("Mathew", "Mary") )  '  comparing strings
VB

To compare your own objects, you need to implement the IComparable interface on your object. Then, you need to create a CompareTo method inside your object, which defines the rules for comparing your object to other objects. Often, you will want to compare your object only to other objects of the same type. For instance, how do you compare a car object to a tree object? You might suggest comparing the weights of the objects, but you could also compare the shape or color of the objects. This is what you need to decide when defining the CompareTo method, and unless you are certain that comparisons to other types are acceptable, you should inform the user that such comparisons are not supported, or are undefined.

In the next sample, you make an object that implements the IComparable interface, and also defines a CompareTo method for comparing itself to other objects. Note that you can only compare this object to its own data type, and not other data types. If the comparable object is not MyType, an ArgumentException is thrown.


Public Class MyType : Implements IComparable

	Private _value As Integer

	Public Sub New(value As Integer)
		MyBase.New()
		_value = value
	End Sub

	Public Function CompareTo (o As Object) As Integer _
				Implements IComparable.CompareTo
		If (Not (TypeOf(o) is MyType))
			Throw New ArgumentException ("o must be of type 'MyType'")
		End If

		Dim v As MyType = CType (o, MyType)

		Return _value - v._value
	End Function

	Overrides Public Function  ToString () As String

		Return String.Format ("MyType({0})", _value)
	End Function
End Class
VB

Now that you have defined the object, you can use the above Max routine for the base data types. The following sample compares two objects of MyType. It's a good idea to flow through the logic, and see how the IComparable interface is used within the Max method, to compare one of the objects to the other. Note that inside the Max method, you invoke CompareTo on the MyType object.


Dim t1 As MyType = new MyType (12)
Dim t2 As MyType = new MyType (17)

Console.WriteLine ( Max (t1, t2) )  '  comparing MyTypes
VB

Summary

All the base data types can be compared because they support the IComparable interface. To compare objects, use the CompareTo method on one of the objects, passing the object you want to compare as a parameter. The rules for the comparison are defined by the CompareTo method for the object in question. You can create your own objects that may be compared to each other by implementing the IComparable interface on the object, and defining a CompareTo method within it.


Copyright 2001-2002 Microsoft Corporation. All rights reserved.