While trying to verify to myself, that C# Equals for IEnumerables is a reference equals, I found something odd. With the following setup in NUnit
var a = (IEnumerable<string>)(new[] { "one", "two" });
var b = (IEnumerable<string>)(new[] { "one", "two" });
this test
Assert.IsFalse(a.Equals(b));
passes, while this test
Assert.AreNotEqual(a, b);
doesn’t. Can anybody explain why?
Edit: Thanks for the answers. I just read the documentation for NUnit, and it says the same thing, that AreEqual and AreNotEqual with collections test for equality of each element of the collection. I guess I was stuck with the notion, that AreEqual and AreNotEqual was just using plain Equals.
The call to
a.Equals(b)returnsfalsebecause a and b are not the same objects (though they are of course identical enumerations). TheEqualsmethod, unless overridden, automatically compares objects by their reference, which is what is happening in this case.Assert.AreNotEqualis a bit more clever than this. It is designed for debugging purposes, unlike theEqualsmethod, so it in fact compares the sequences yielded by the two enumerations, since it recognisesIEnumerable<T>as a special type. You should also notice that it does other interesting things, such as returningtruewhen the two parameters are numerically identical but of different value types (e.g.shortandlong).Hope that helps.