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
Byte.Equals(Object) Method in C#
The Byte.Equals(Object) method in C# returns a value indicating whether this instance is equal to a specified object. This method compares the current byte instance with another object and returns true if they are equal, false otherwise.
Syntax
Following is the syntax −
public override bool Equals (object obj);
Parameters
obj − An object to compare with this instance, or
null.
Return Value
Returns true if obj is a byte instance and equals the value of this instance; otherwise, false.
Example
Let us now see an example to implement the Byte.Equals(Object) method −
using System;
public class Demo {
public static void Main() {
byte b1 = 5;
object b2 = (byte)0; // 5/10 = 0 when cast to byte
if (b1.Equals(b2))
Console.WriteLine("b1 = b2");
else
Console.WriteLine("b1 is not equal to b2");
}
}
The output of the above code is −
b1 is not equal to b2
Using Equals with Same Values
Here's an example demonstrating when the method returns true −
using System;
public class Demo {
public static void Main() {
byte b1 = 10;
object b2 = (byte)10;
Console.WriteLine("b1 = " + b1);
Console.WriteLine("b2 = " + b2);
Console.WriteLine("b1.Equals(b2): " + b1.Equals(b2));
// Comparing with non-byte object
object b3 = 10; // This is an int, not byte
Console.WriteLine("b1.Equals(10 as int): " + b1.Equals(b3));
}
}
The output of the above code is −
b1 = 10 b2 = 10 b1.Equals(b2): True b1.Equals(10 as int): False
Type-Specific Comparison
The method performs type-specific comparison and only returns true if both the type and value match −
using System;
public class Demo {
public static void Main() {
byte b = 255;
Console.WriteLine("Comparing with byte: " + b.Equals((byte)255));
Console.WriteLine("Comparing with int: " + b.Equals(255));
Console.WriteLine("Comparing with string: " + b.Equals("255"));
Console.WriteLine("Comparing with null: " + b.Equals(null));
}
}
The output of the above code is −
Comparing with byte: True Comparing with int: False Comparing with string: False Comparing with null: False
Conclusion
The Byte.Equals(Object) method provides type-safe comparison for byte values. It returns true only when comparing with another byte object of the same value, ensuring both type and value equality for reliable comparisons.
