Freestyle Coding

Programming in the Real World

  Home  |   Contact  |   Syndication    |   Login
  54 Posts | 0 Stories | 41 Comments | 0 Trackbacks

News

Tag Cloud


Archives

Post Categories

Charity

Conferences

Professional

Projects

Social Networks

Thursday, September 15, 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;
}

return Parallel.For( 0, p_lhs.Length, ( _lcv, loopState ) => {
if( !p_lhs.GetValue( _lcv ).Equals( p_rhs.GetValue( _lcv ) ) ) {
loopState.Break();
}
} ).IsCompleted;
}

I use object.Equal in the loops because I'm compairing the ValueTypes that the Loop contains. The use of System.Threading.Tasks.Parallel helps me move things along a little quicker. Parallel.For returns an struct that tells you whether the loop was halted. If I never halted the loop with loopState.Break, then they all matched. If, for some reason, you can't use Parallel.For, just do a for loop that returns false;