Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I thought Object.Equals(Object, Object) support bitwise equality and not value equality

Tags:

c#

Static method Object.Equals(Object, Object) supports reference equality for reference types, and bitwise equality for value types, where with bitwise equality the objects that are compared have the same binary representation, while value equality objects compared have the same value even though they have different binary representations.

For example, since i1 and b1 are of different types, they don't have the same binary representation and thus Object.Equals(Object, Object) returns false:

        int  i1 = 100;
        byte b1 = 100;
        Console.WriteLine(Object.Equals(i1, b1));//false

Object.Equals(Object, Object) should also return false when comparing d1 and d2 ( since the two variables have different binary representation of the same value ), but it instead returns true, which suggests that it compares them using value equality:

        decimal d1 = 1.10M;
        decimal d2 = 1.100M;
        Console.WriteLine(Object.Equals(d1, d2)); //true

Shouldn't Object.Equals(Object, Object) return False when comparing d1 and d2?

From http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx:

For example, consider two Decimal objects that represent the numbers 1.10 and 1.1000. The Decimal objects do not have bitwise equality because they have different binary representations to account for the different number of trailing zeroes.

thanx

like image 346
user702769 Avatar asked Apr 21 '11 18:04

user702769


1 Answers

Decimal is a value type and Equals method actually compares all its fields using Reflection. For more details, please refer to the MSDN:

ValueType.Equals Method

Finally, your scope from the MSDN is incomplete. Here it is:

For example, consider two Decimal objects that represent the numbers 1.10 and 1.1000. The Decimal objects do not have bitwise equality because they have different binary representations to account for the different number of trailing zeroes. However, the objects have value equality because the numbers 1.10 and 1.1000 are considered equal for comparison purposes since the trailing zeroes are insignificant.

like image 53
DevExpress Team Avatar answered Oct 19 '22 22:10

DevExpress Team