C# CompareTo Int Method

The C# programming language

You want to understand the results of the CompareTo method on the int type in the C# programming language. This method is called upon an int value, and you must pass another int value to compare with.

5.CompareTo(6) = -1      First int is smaller.
6.CompareTo(5) =  1      First int is larger.
5.CompareTo(5) =  0      Ints are equal.

Examples

To begin, this program uses three int values; they can be specified as const but this is not important. Next, the variables ab, ba, and ca contain the results of the ints a, b, and c compared to one another. You can see that when the first number is larger, the result is 1; when the first number is smaller, the result is -1; and when the numbers are equal, the result is 0.

This C# example program reveals the results of the CompareTo method.

Program that uses CompareTo method on int [C#]

using System;

class Program
{
    static void Main()
    {
	const int a = 5;
	const int b = 6;
	const int c = 5;

	int ab = a.CompareTo(b);
	int ba = b.CompareTo(a);
	int ca = c.CompareTo(a);

	Console.WriteLine(ab);
	Console.WriteLine(ba);
	Console.WriteLine(ca);
    }
}

Output

-1
1
0

Uses

Note (please read)

The CompareTo method is most useful in implementing sorting routines. The articles listed here show how you can use CompareTo when implementing IComparable; when implementing Comparison delegate target methods; and when implementing Comparisons with lambda expressions.

IComparable Example With CompareTo Sort KeyValuePair List Sort Tuple List

Summary

CompareTo provides a standard way to determine which of two numbers is larger. The result is always 1, -1, or 0; these values correspond to a larger, smaller, or equal first number. You can find more information about CompareTo on the string type in a separate tutorial.

String.Compare Method Sort Examples
.NET