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.Equals(Object) Method in C#
The Boolean.Equals(Object) method in C# returns a value indicating whether the current Boolean instance is equal to a specified object. This method compares the Boolean value with another object, returning true only if the object is also a Boolean with the same value.
Syntax
Following is the syntax −
public override bool Equals (object obj);
Parameters
obj − An object to compare with this Boolean instance.
Return Value
Returns true if the object is a Boolean instance with the same value; otherwise, false.
Using Boolean.Equals() with Different Data Types
Example
using System;
public class Demo {
public static void Main() {
bool val1 = true;
object val2 = 5/10;
Console.WriteLine("val1 = " + val1);
Console.WriteLine("val2 = " + val2 + " (Type: " + val2.GetType() + ")");
if (val1.Equals(val2))
Console.WriteLine("Both are equal!");
else
Console.WriteLine("Both aren't equal!");
}
}
The output of the above code is −
val1 = True val2 = 0 (Type: System.Int32) Both aren't equal!
Using Boolean.Equals() with Boolean Objects
Example
using System;
public class Demo {
public static void Main() {
bool val1 = true;
object val2 = true;
object val3 = false;
object val4 = "true";
Console.WriteLine("Comparing " + val1 + " with " + val2 + ": " + val1.Equals(val2));
Console.WriteLine("Comparing " + val1 + " with " + val3 + ": " + val1.Equals(val3));
Console.WriteLine("Comparing " + val1 + " with " + val4 + ": " + val1.Equals(val4));
}
}
The output of the above code is −
Comparing True with True: True Comparing True with False: False Comparing True with true: False
Comparing with Null Values
Example
using System;
public class Demo {
public static void Main() {
bool val1 = false;
object val2 = null;
bool val3 = true;
Console.WriteLine("Comparing " + val1 + " with null: " + val1.Equals(val2));
Console.WriteLine("Comparing " + val3 + " with null: " + val3.Equals(val2));
}
}
The output of the above code is −
Comparing False with null: False Comparing True with null: False
Key Points
-
The method returns
trueonly if the object is a Boolean with the same value. -
Comparing with different data types (int, string, etc.) always returns
false. -
Comparing with
nullalways returnsfalse. -
The comparison is case-sensitive for the underlying value, not string representation.
Conclusion
The Boolean.Equals(Object) method provides a reliable way to compare Boolean values with objects. It returns true only when comparing with another Boolean instance that has the same value, making it useful for type-safe Boolean comparisons in object-oriented scenarios.
