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
Boolean.CompareTo(Object) Method in C#
The Boolean.CompareTo(Object) method in C# compares the current Boolean instance to a specified object and returns an integer that indicates their relationship to one another. This method is useful for sorting Boolean values or implementing custom comparison logic.
Syntax
Following is the syntax −
public int CompareTo(object obj);
Where obj is an object to compare to this instance, or null.
Return Value
The method returns an integer value indicating the relationship between the current instance and the specified object −
Less than zero: This instance is
falseandobjistrueZero: This instance and
objhave the same Boolean valueGreater than zero: This instance is
trueandobjisfalse, orobjis null
Using CompareTo() with Same Values
Example
using System;
public class Demo {
public static void Main() {
bool b1 = false;
object b2 = false;
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");
Console.WriteLine("Comparison result: " + res);
}
}
The output of the above code is −
b1 = b2 Comparison result: 0
Using CompareTo() with Different Values
Example
using System;
public class Demo {
public static void Main() {
bool b1 = false;
object b2 = true;
int res1 = b1.CompareTo(b2);
Console.WriteLine("false.CompareTo(true) = " + res1);
bool b3 = true;
object b4 = false;
int res2 = b3.CompareTo(b4);
Console.WriteLine("true.CompareTo(false) = " + res2);
bool b5 = true;
object nullObj = null;
int res3 = b5.CompareTo(nullObj);
Console.WriteLine("true.CompareTo(null) = " + res3);
}
}
The output of the above code is −
false.CompareTo(true) = -1 true.CompareTo(false) = 1 true.CompareTo(null) = 1
Handling Invalid Object Types
When the object passed is not a Boolean type, the method throws an ArgumentException −
Example
using System;
public class Demo {
public static void Main() {
bool b1 = true;
object invalidObj = "Hello";
try {
int res = b1.CompareTo(invalidObj);
Console.WriteLine("Result: " + res);
}
catch (ArgumentException ex) {
Console.WriteLine("Exception: " + ex.Message);
}
}
}
The output of the above code is −
Exception: Object must be of type Boolean.
Conclusion
The Boolean.CompareTo(Object) method provides a standardized way to compare Boolean values, returning negative, zero, or positive integers based on the comparison. It treats false as less than true and handles null objects by considering them less than any Boolean value.
