EqualsBuilder and HashCodeBuilder

Jan 12, 2011 at 9:33 AM

Is it possible or necessary to implement the EqualsBuilder and HashCodeBuilder (like in apache-Commons) into one of the next releases?

Jan 12, 2011 at 8:10 PM

With extremely minimal testing, this should work......

 

public class EqualsBuilder
{
int returnValue = 0;

public EqualsBuilder Test<T>(T lhs, T rhs) where T: IComparable<T>
{
if (returnValue == 0)
returnValue = lhs.CompareTo(rhs);
return this;
}

public EqualsBuilder Test<T>(T[] lhs, T[] rhs)   where T : IComparable<T>
{
return Test<T>((IEnumerable<T>) lhs, (IEnumerable<T>) rhs);
}

public EqualsBuilder Test<T>(IEnumerable<T> lhs, IEnumerable<T> rhs)   where T : IComparable<T>
{
if (returnValue == 0)
{
var rhsIter = rhs.GetEnumerator();
foreach (var lhsItem in lhs)
{
if (!rhsIter.MoveNext())
returnValue = -1;
else
returnValue = lhsItem.CompareTo(rhsIter.Current);

if (returnValue != 0)
break;
}
if (returnValue == 0 && rhsIter.MoveNext())
returnValue = 1;
}
return this;
}

public bool IsEqual { get { return returnValue == 0; } }
public int CompareTo { get { return returnValue;  } }

}

 

 

Here's the code I used to test it:

class Program
{
static void Main(string[] args)
{
var a1 = new TestClass(1, 2.0f, "CCC", 5L);
var b1 = new TestClass(1, 5.0f, "CCC", 5L);
var c1 = new TestClass(1, 2.0f, "CCC", 3L);

Console.WriteLine(a1.Equals(a1));
Console.WriteLine(a1.Equals(b1));
Console.WriteLine(a1.Equals(c1));

Console.WriteLine(a1.CompareTo(a1));
Console.WriteLine(a1.CompareTo(b1));
Console.WriteLine(a1.CompareTo(c1));

}
}
class TestClass : IEquatable<TestClass>, IComparable<TestClass>
{
int A;
float B;
string C;
long[] D;

public TestClass(int a, float b, string c, long d)
{
A = a;
B = b;
C = c;
D = new long[] { d, d, d, d };
}



#region IEquatable<TestClass> Members

public bool Equals(TestClass other)
{
return new EqualsBuilder()
.Test(this.A, other.A)
.Test(this.B, other.B)
.Test(this.C, other.C)
.Test(this.D, other.D)
.IsEqual;
}

#endregion

#region IComparable<TestClass> Members

public int CompareTo(TestClass other)
{
return new EqualsBuilder()
.Test(this.A, other.A)
.Test(this.B, other.B)
.Test(this.C, other.C)
.Test(this.D, other.D)
.CompareTo;
}

#endregion
}

 

 


Jan 18, 2011 at 3:59 PM

For the first step this looks quite nice.

But target will be some kind of reflection solution.