AssertFailedException: CollectionAssert.AreEqual failed (Element at index 0 do not match)

Артур Кузнецов 21 Reputation points
2022-04-25T12:12:16.617+00:00

Why this method fails with message: "CollectionAssert.AreEqual failed. (Element at index 0 do not match.)"?

[TestMethod]
        public void Listest()
        {
            List<int[]> first = new List<int[]>()
            {
                new int[] { 1, 3, 5 }
            };

            List<int[]> second = new List<int[]>()
            {
                new int[] { 1, 3, 5 }
            };
            CollectionAssert.AreEqual(first, second);
        }

But code below works fine:

[TestMethod]
        public void Listest()
        {
            int[] arr = new int[] { 1, 3, 5 };
            List<int[]> first = new List<int[]>()
            {
                arr
            };

            List<int[]> second = new List<int[]>()
            {
                arr
            };
            CollectionAssert.AreEqual(first, second);
        }
Developer technologies | Visual Studio | Testing
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-04-25T14:35:39.567+00:00

    Because the first test is a list of arrays. Arrays are reference types and the only way for first[0] to be equal to second[0] is if they are the same object. Reference types follow reference semantics meaning 2 objects are equal only if they are the same object.

    In the second test you are using the same array in both lists. Since first[0] is the same array/object as second[0] then they are equal. You can confirm they are the same object by changing an element (e.g. arr[1] to 10). Both lists will see the change because they both have the same object in their list.

    Refer to the docs here on how equality works in .NET.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.