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
Byte.CompareTo(Object) Method in C#
The Byte.CompareTo(Object) method in C# compares the current byte instance to a specified object and returns an integer that indicates their relative values. This method is useful for sorting operations and determining the ordering relationship between byte values.
Syntax
Following is the syntax −
public int CompareTo(object val);
Parameters
val − An object to compare, or null.
Return Value
The method returns an integer with the following meaning −
-
Less than zero − The current instance is less than the value.
-
Zero − The current instance is equal to the value.
-
Greater than zero − The current instance is greater than the value.
Example
Basic Comparison Example
Let us see an example demonstrating the Byte.CompareTo(Object) method −
using System;
public class Demo {
public static void Main() {
byte b1 = 5;
object b2 = (byte)5;
int res = b1.CompareTo(b2);
if (res > 0)
Console.WriteLine("b1 > b2");
else if (res < 0)
Console.WriteLine("b1 < b2");
else
Console.WriteLine("b1 = b2");
}
}
The output of the above code is −
b1 = b2
Multiple Comparisons Example
using System;
public class Demo {
public static void Main() {
byte b1 = 10;
byte b2 = 5;
byte b3 = 15;
Console.WriteLine("Comparing 10 with 5: " + b1.CompareTo((object)b2));
Console.WriteLine("Comparing 10 with 15: " + b1.CompareTo((object)b3));
Console.WriteLine("Comparing 10 with 10: " + b1.CompareTo((object)(byte)10));
// Null comparison
Console.WriteLine("Comparing 10 with null: " + b1.CompareTo(null));
}
}
The output of the above code is −
Comparing 10 with 5: 1 Comparing 10 with 15: -1 Comparing 10 with 10: 0 Comparing 10 with null: 1
Key Rules
-
If the parameter is
null, the method returns a positive value (1). -
The parameter must be a
byteobject, otherwise anArgumentExceptionis thrown. -
This method implements the
IComparableinterface.
Conclusion
The Byte.CompareTo(Object) method provides a standardized way to compare byte values, returning negative, zero, or positive integers based on the relative ordering. This method is essential for sorting operations and implementing comparison logic in applications that work with byte data.
