Update: The javascript on this blog has been suppressed by the blogger's parser. Consequently, some of the functionality may not work. Inconvenience is regretted.

Thursday, May 7, 2009

Comparing two objects for equality [Value Equality]

There could be numerous implementations for comparing two objects for equality. Here is the generic implementation of the comparer I have been using:

namespace Utilities
{
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class ComparerUtil
{
public static bool ValueEquals<T>(T lhs, T rhs)
where T : class
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream lhsStream = new MemoryStream();
MemoryStream rhsStream = new MemoryStream();

try
{
if ((lhs == null) && (rhs == null))
return true;
if ((lhs == null) || (rhs == null))
return false;
formatter.Serialize(lhsStream, lhs);
formatter.Serialize(rhsStream, rhs);

byte[] lhsByteArray = lhsStream.ToArray();
byte[] rhsByteArray = rhsStream.ToArray();

return ArrayValueEquals(lhsByteArray, rhsByteArray);
}
finally
{
lhsStream.Close();
rhsStream.Close();
}
}

public static bool ArrayValueEquals<T>(T[] lhsArray, T[] rhsArray)
{
if (lhsArray.Length != rhsArray.Length)
return false;

for (int index = 0; index < lhsArray.Length; ++index)
if (!lhsArray[index].Equals(rhsArray[index]))
return false;

return true;
}
}
}

The above implementation does a byte-by-byte comparison after serializing the two objects in question to binary format. This means that the two objects being compared must be serializable. Note the usage of generics which are available only .Net 2.0 upwards. If you are using .Net 3.5 (which is cool ;)), consider writing the implementation using Extension Methods.

Cheers,
Pushp