HomeSearch

C# CompareTo Int Method

Learn about CompareTo, which is used to determine whether one element is sorted earlier or later.
CompareTo. This method acts upon 2 numbers. It returns an int value. 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.Compare, CompareTo
CompareTo results 5.CompareTo(6) = -1 First int is smaller. 6.CompareTo(5) = 1 First int is larger. 5.CompareTo(5) = 0 Ints are equal.
To begin, this program uses 3 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.Int, uint

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.

C# program that uses CompareTo method on int 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. The CompareTo method is most useful in implementing sorting routines. The articles listed here show how to use CompareTo when implementing IComparable, Comparison delegate target methods, and Comparisons with lambda expressions.IComparableSort KeyValuePair ListSort Tuple
Summary. CompareTo provides a standard way to determine which of two numbers is larger. The result of this method is always 1, -1 or 0. These values correspond to a larger, smaller, or equal first number.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls