1

I have read a lot of answers, but I have not found one that solves my problem. I wrote the following Matrix class, which contains 2 methods to check Equality: one overridden from the base class and the other from IEquatable<Matrix>.

Here are the methods:

public override bool Equals(object obj)
{
    return Equals(obj as Matrix);
}

public bool Equals(Matrix other)
{
    if (RowsCount != other.RowsCount || ColumnsCount != other.ColumnsCount)
        return false;
    for (int i = 0; i < RowsCount; i++)
    {
        for (int j = 0; j < ColumnsCount; j++)
        {
            if (Math.Abs(Values[i][j] - other.Values[i][j]) > EqDiff)
                return false;
        }
    }
    return true;
}

It works as expected when I check for equality in code like this:

Matrix M1 = new Matrix(new[]{
                      new double[] {1, 2, 0},
                      new double[] {-1, 1, 1},
                      new double[] {1, 0, 0}
});
Matrix M2 = new Matrix(new[]{
                      new double[] {0, 5, 3},
                      new double[] {1, 2, 8},
                      new double[] {4, 5, 6}
});
Matrix M1sumM2 = new Matrix(new[]{
                      new double[] {1, 7, 3},
                      new double[] {0, 3, 9},
                      new double[] {5, 5, 6}
});
Matrix r = M1 + M2;
bool e = M1sumM2.Equals(r); //here I got true

but when I call Assert.AreEqual it returns false.

verdammelt
  • 922
  • 10
  • 22
Iworb
  • 522
  • 7
  • 29
  • 2
    Not an answer to your question but you must add a null check in your `Equals(Matrix other)` method. Otherwise every call to `Equals` with a type other than `Matrix` will cause a NullReferenceException. – Dirk Jan 13 '14 at 12:12
  • I think, that problem dissapear, when I 1) set `r` to null and than 2) calculate sum. I don't know how, but after this it began to work... – Iworb Jan 13 '14 at 12:17
  • Have you used a debugger to see which Equal call is called by Assert.Equals? – verdammelt Jan 16 '14 at 04:29
  • Have you overrided `GetHashCode` method too? – Tony Jan 16 '14 at 04:38

0 Answers0