Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
UInt32.CompareTo() Method in C# with Examples
The UInt32.CompareTo() method in C# is used to compare the current instance to a specified object or UInt32 and returns an indication of their relative values. This method is essential for sorting operations and determining the ordering relationship between unsigned 32-bit integers.
Syntax
The UInt32.CompareTo() method has two overloads −
public int CompareTo(object value); public int CompareTo(uint value);
Parameters
value (object) − An object to compare, or null.
value (uint) − An unsigned integer to compare.
Return Value
The method returns an int that indicates the relative order of the values being compared −
Less than zero − The current instance is less than the specified value.
Zero − The current instance is equal to the specified value.
Greater than zero − The current instance is greater than the specified value.
Using CompareTo() with UInt32 Values
Example
using System;
public class Demo {
public static void Main() {
uint val1 = 25;
uint val2 = 55;
int res = val1.CompareTo(val2);
Console.WriteLine("Return value (comparison) = " + res);
if (res > 0)
Console.WriteLine("val1 > val2");
else if (res < 0)
Console.WriteLine("val1 < val2");
else
Console.WriteLine("val1 = val2");
}
}
The output of the above code is −
Return value (comparison) = -1 val1 < val2
Using CompareTo() with Object Parameter
Example
using System;
public class Demo {
public static void Main() {
uint val1 = 25;
object val2 = (uint)2;
int res = val1.CompareTo(val2);
Console.WriteLine("Return value (comparison) = " + res);
if (res > 0)
Console.WriteLine("val1 > val2");
else if (res < 0)
Console.WriteLine("val1 < val2");
else
Console.WriteLine("val1 = val2");
}
}
The output of the above code is −
Return value (comparison) = 1 val1 > val2
Using CompareTo() for Sorting
Example
using System;
public class Demo {
public static void Main() {
uint[] values = { 45, 12, 78, 23, 56 };
Console.WriteLine("Original array:");
foreach (uint val in values) {
Console.Write(val + " ");
}
Array.Sort(values, (x, y) => x.CompareTo(y));
Console.WriteLine("\nSorted array:");
foreach (uint val in values) {
Console.Write(val + " ");
}
}
}
The output of the above code is −
Original array: 45 12 78 23 56 Sorted array: 12 23 45 56 78
Conclusion
The UInt32.CompareTo() method provides a standardized way to compare unsigned 32-bit integers, returning -1, 0, or 1 to indicate less than, equal to, or greater than relationships. This method is particularly useful for sorting operations and implementing custom comparison logic in applications.
