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(Boolean) Method in C#
The Boolean.CompareTo(Boolean) method in C# is used to compare the current Boolean instance with another Boolean object and returns an integer indicating their relative values.
Syntax
Following is the syntax −
public int CompareTo(bool value);
Parameters
value − A Boolean object to compare with the current instance.
Return Value
The method returns an integer value −
-
-1 − if the current instance is
falseandvalueistrue -
0 − if the current instance and
valueare equal -
1 − if the current instance is
trueandvalueisfalse
Example 1 - Comparing Equal Values
using System;
public class Demo {
public static void Main() {
bool b1 = false;
bool b2 = false;
int result = b1.CompareTo(b2);
Console.WriteLine("b1: " + b1);
Console.WriteLine("b2: " + b2);
Console.WriteLine("b1.CompareTo(b2): " + result);
if (result > 0)
Console.WriteLine("b1 > b2");
else if (result < 0)
Console.WriteLine("b1 < b2");
else
Console.WriteLine("b1 = b2");
}
}
The output of the above code is −
b1: False b2: False b1.CompareTo(b2): 0 b1 = b2
Example 2 - Comparing Different Values
using System;
public class Demo {
public static void Main() {
bool b1 = false;
bool b2 = true;
bool b3 = true;
bool b4 = false;
Console.WriteLine("false.CompareTo(true): " + b1.CompareTo(b2));
Console.WriteLine("true.CompareTo(false): " + b3.CompareTo(b4));
Console.WriteLine("true.CompareTo(true): " + b3.CompareTo(b2));
}
}
The output of the above code is −
false.CompareTo(true): -1 true.CompareTo(false): 1 true.CompareTo(true): 0
Using CompareTo for Sorting
using System;
public class Demo {
public static void Main() {
bool[] boolArray = { true, false, true, false, true };
Console.WriteLine("Original array:");
foreach (bool b in boolArray) {
Console.Write(b + " ");
}
Array.Sort(boolArray);
Console.WriteLine("\nSorted array:");
foreach (bool b in boolArray) {
Console.Write(b + " ");
}
}
}
The output of the above code is −
Original array: True False True False True Sorted array: False False True True True
Conclusion
The Boolean.CompareTo(Boolean) method provides a standardized way to compare Boolean values, returning -1, 0, or 1 based on the relationship. In Boolean ordering, false is considered less than true, making this method useful for sorting and comparison operations.
