Byte.Equals(Byte) Method in C#

The Byte.Equals(Byte) method in C# returns a value indicating whether this instance and a specified Byte object represent the same value. This method provides a reliable way to compare two byte values for equality.

Syntax

Following is the syntax −

public bool Equals(byte obj);

Parameters

obj − A byte object to compare to this instance.

Return Value

Returns true if obj has the same value as this instance; otherwise, false.

Using Byte.Equals() for Value Comparison

Example

using System;
public class Demo {
   public static void Main(){
      byte b1, b2;
      b1 = 5;
      b2 = 5;
      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 = b2

Comparing Different Byte Values

Example

using System;
public class Demo {
   public static void Main(){
      byte b1 = 10;
      byte b2 = 20;
      byte b3 = 10;
      
      Console.WriteLine("b1.Equals(b2): " + b1.Equals(b2));
      Console.WriteLine("b1.Equals(b3): " + b1.Equals(b3));
      Console.WriteLine("b2.Equals(b3): " + b2.Equals(b3));
   }
}

The output of the above code is −

b1.Equals(b2): False
b1.Equals(b3): True
b2.Equals(b3): False

Comparison with Equality Operator

The Byte.Equals() method provides the same result as the equality operator (==) for byte values −

Example

using System;
public class Demo {
   public static void Main(){
      byte a = 15;
      byte b = 15;
      byte c = 25;
      
      Console.WriteLine("Using Equals() method:");
      Console.WriteLine("a.Equals(b): " + a.Equals(b));
      Console.WriteLine("a.Equals(c): " + a.Equals(c));
      
      Console.WriteLine("\nUsing == operator:");
      Console.WriteLine("a == b: " + (a == b));
      Console.WriteLine("a == c: " + (a == c));
   }
}

The output of the above code is −

Using Equals() method:
a.Equals(b): True
a.Equals(c): False

Using == operator:
a == b: True
a == c: False

Conclusion

The Byte.Equals(Byte) method provides a straightforward way to compare byte values for equality. It returns true when both byte values are identical and false otherwise, offering the same functionality as the equality operator for primitive byte comparisons.

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

368 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements