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.

Byte.CompareTo() Return Values < 0 Current byte is smaller 5.CompareTo(10) = 0 Current byte is equal 5.CompareTo(5) > 0 Current byte is larger 10.CompareTo(5) Perfect for sorting and ordering operations Throws ArgumentException if object is not a byte

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 byte object, otherwise an ArgumentException is thrown.

  • This method implements the IComparable interface.

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.

Updated on: 2026-03-17T07:04:35+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements