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
SByte.CompareTo() Method in C# with Examples
The SByte.CompareTo() method in C# is used to compare the current sbyte instance to a specified object or sbyte value and returns an integer that indicates their relative ordering. This method is essential for sorting operations and comparison logic.
Syntax
The SByte.CompareTo() method has two overloads −
public int CompareTo(sbyte value); public int CompareTo(object obj);
Parameters
-
value − An 8-bit signed integer to compare with the current instance.
-
obj − An object to compare with the current instance, or null.
Return Value
The method returns an integer that indicates the relative ordering −
-
Less than zero − Current instance is less than the parameter
-
Zero − Current instance equals the parameter
-
Greater than zero − Current instance is greater than the parameter
Using CompareTo() with SByte Values
Example
using System;
public class Demo {
public static void Main() {
sbyte s1 = 55;
sbyte s2 = 55;
Console.WriteLine("Value of S1 = " + s1);
Console.WriteLine("Value of S2 = " + s2);
int res = s1.CompareTo(s2);
if (res > 0)
Console.WriteLine("s1 > s2");
else if (res < 0)
Console.WriteLine("s1 < s2");
else
Console.WriteLine("s1 = s2");
}
}
The output of the above code is −
Value of S1 = 55 Value of S2 = 55 s1 = s2
Using CompareTo() with Object Parameter
Example
using System;
public class Demo {
public static void Main() {
sbyte s1 = 55;
object s2 = (sbyte)55;
Console.WriteLine("Value of S1 = " + s1);
Console.WriteLine("Value of S2 = " + s2);
int res = s1.CompareTo(s2);
if (res > 0)
Console.WriteLine("s1 > s2");
else if (res < 0)
Console.WriteLine("s1 < s2");
else
Console.WriteLine("s1 = s2");
}
}
The output of the above code is −
Value of S1 = 55 Value of S2 = 55 s1 = s2
Using CompareTo() for Different Values
Example
using System;
public class Demo {
public static void Main() {
sbyte val1 = 10;
sbyte val2 = 25;
sbyte val3 = 5;
Console.WriteLine("Comparing " + val1 + " with " + val2 + ": " + val1.CompareTo(val2));
Console.WriteLine("Comparing " + val2 + " with " + val3 + ": " + val2.CompareTo(val3));
Console.WriteLine("Comparing " + val3 + " with " + val1 + ": " + val3.CompareTo(val1));
// Using with null object
object nullObj = null;
Console.WriteLine("Comparing " + val1 + " with null: " + val1.CompareTo(nullObj));
}
}
The output of the above code is −
Comparing 10 with 25: -1 Comparing 25 with 5: 1 Comparing 5 with 10: -1 Comparing 10 with null: 1
Conclusion
The SByte.CompareTo() method provides a reliable way to compare sbyte values, returning negative, zero, or positive integers based on the relative ordering. It supports both direct sbyte comparisons and object-based comparisons, making it useful for sorting algorithms and conditional logic.
