This is a mirror of official site: http://jasper-net.blogspot.com/

Arrays of ValueTypes don't like object.Equals

| Monday, September 19, 2011
This had me pulling my hair out for a couple days:
byte[] _A = new byte[64];
// Fill _A with some meaningful, valid data.

byte[] _B = new byte[_A.Length];
_A.CopyTo( _B, 0 );

if( !_A.Equals( _B ) ) {
throw new WtfException(
"It appears object.Equals doesn't work on arrays of value types..."
);
}

Yes, that throws the WtfException. It took me a few days to notice. byte is a ValueType. However, byte[] is a System.Array, which is a reference type. As per the .NET documenation:

    The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

_A and _B are not references to the same array. Thus, they are not equal. You need to make something like this:

private static bool ValueTypeArraysAreEqual( Array p_lhs, Array p_rhs ) {
if( p_lhs == null ) {
return p_rhs == null;
}

if( p_rhs == null ) {
return false;
}

if( p_lhs.Length != p_rhs.Length ) {
return false;
}


Read more: Freestyle Coding
QR: arrays-of-valuetypes-dont-like-object.equals.aspx

Posted via email from Jasper-net

0 comments: