CompareTo. This method acts upon 2 values (like strings or numbers). It returns an int value. The returned value (-1, 1 or 0) tells us which of the 2 numbers is bigger.
When using CompareTo, we usually return directly the value of the method call. This enables us to easily implement comparisons for sorting in C#.
Input and output. A negative one indicates the first value is smaller. A positive one indicates the first value is bigger. And a zero indicates the two values are equal.
5.CompareTo(6) = -1 First int is smaller.
6.CompareTo(5) = 1 First int is larger.
5.CompareTo(5) = 0 Ints are equal.
An example. This program uses 3 int values. Next, the variables "ab", "ba", and "ca" contain the results of the ints "a", "b", and "c" compared to one another.
Here We 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. These values are written to the console.
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);
}
}-1
1
0
Uses. The CompareTo method is most useful in implementing sorting routines. We use CompareTo when implementing IComparable, Comparison delegate target methods, and Comparisons with lambdas.
A summary. CompareTo provides a standard way to determine which of two numbers is larger. The result tells us if a number comparison is larger, smaller, or equal.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 12, 2022 (edit).