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 false and value is true

  • 0 − if the current instance and value are equal

  • 1 − if the current instance is true and value is false

Boolean.CompareTo() Return Values false.CompareTo(true) -1 false < true Same Values 0 Equal true.CompareTo(false) 1 true > false In Boolean ordering: false < true

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.

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

669 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements