Comparer: Compare

Compare

Performs a case-sensitive comparison of two values of the same type and returns a value indicating whether one is less than, equal to, or greater than the other.



 Public Function Compare(
	  ByRef a As Variant,
	  ByRef b As Variant ) As Long

Parameters

a
[ByRef] Variant. The left-hand-side of the equation.
b
[ByRef] Variant. the right-hand-side of the equation.

Return Values

Long -  A signed integer that indicates the relative values of a and b, as shown in the following table.
Value Meaning
Less than zeroa is less than b.
Zeroa equals b.
Greater than zeroa is greater than b.

Remarks

If a implements IComparable, then a.CompareTo(b) is returned; otherwise, if b implements IComparable, then the negated result of b.CompareTo(a) is returned.

String comparisons might have different results depending on the culture.

Exceptions

ExceptionCondition
ArgumentException Neither a nor b implements the IComparable interface.
-or-
a and b are of different types and cannot be compared.

Examples

The following code example shows how Compare returns different values depending on the culture associated with the Comparer.

Public Sub Main()
    Const Str1 As String = "Apple"
    Const Str2 As String = "Æble"
    
    Debug.Print CorString.Format("Comparing ""{0}"" and ""{1}"" ...", Str1, Str2)
    
    Debug.Print CorString.Format("          Invariant Comparer: {0}", Comparer.DefaultInvariant.Compare(Str1, Str2))
    
    Dim CompUS As Comparer
    Set CompUS = NewComparer(NewCultureInfo("en-US", False))
    Debug.Print CorString.Format("English (United States) Sort: {0}", CompUS.Compare(Str1, Str2))
    
    Dim CompDK As Comparer
    Set CompDK = NewComparer(NewCultureInfo("da-DK", False))
    Debug.Print CorString.Format("        dansk (Danmark) Sort: {0}", CompDK.Compare(Str1, Str2))
    
End Sub

' This code produces the following output.
'
'    Comparing "Apple" and "Æble" ...
'              Invariant Comparer: 1
'    English (United States) Sort: 1
'            dansk (Danmark) Sort: -1

See Also

Project CorLib Overview

Class Comparer Overview

IComparable

CultureInfo