0

Trying to compare 2 arrays but not getting it to work

            Console.WriteLine("Entering elements for ths 1st array: ");
        int[] arr1 = new int[3];
        for (int i = 0; i < arr1.Length; i++)
        {
            arr1[i] = Convert.ToInt32(Console.ReadLine());
        }
        Console.WriteLine("Entering the elements for the 2nd array: ");
        int[] arr2 = new int[3];
        for (int i = 0; i < arr2.Length; i++)
        {
            arr2[i] = Convert.ToInt32(Console.ReadLine());
        }
        bool result = Array.Equals(arr1,arr2);
        if (result)
        {
            Console.WriteLine("Equal");
        }
        else
        {
            Console.WriteLine("Not equal");
        }
    }

I keep on getting a Not equal

user544079
  • 16,109
  • 42
  • 115
  • 171
  • possible duplicate of [Testing Equality of Arrays in C#](http://stackoverflow.com/questions/649444/testing-equality-of-arrays-in-c-sharp) – ChrisWue Feb 01 '13 at 20:32

4 Answers4

3

This doesn't work because Array.Equals() runs Object.Equals method - it compares just references. Use Enumerable.SequenceEqual() instead for example.

Anthony
  • 500
  • 3
  • 14
0

You are not comparing the values stored in the arrays but you are comparing two different instances of an integer array. (the references).
Of course they are different.

If you want to check only if the two arrays contains the same values you could use the SequenceEquals LinQ operator, if you wish to get the difference between the two arrays use Except

if(arr1.SequenceEquals(arr2))
     Console.WriteLine("Equals");
else
     Console.WriteLine("Not equal");

....

int[] diff =  arr1.Except(arr2).ToArray();
if(diff.Length == 0) 
     Console.WriteLine("Equals");
else
     Console.WriteLine("Not equal");
Steve
  • 213,761
  • 22
  • 232
  • 286
  • If you're going to use `LINQ`, just use `SequenceEqual`. It can short circuit, unlike `Except`. It also is shorter, and semantically represents what you want to do. Oh, and `Except` doesn't return an array, it returns an `IEnumerable`, and so you'd need to use `Count`, or better yet, `Any`, instead of `Length`. – Servy Feb 01 '13 at 20:38
  • @Servy OMG you are fast. wait – Steve Feb 01 '13 at 20:43
0

That will never work. These are two different instances of the array. Equals is inherited from Object.

epitka
  • 17,275
  • 20
  • 88
  • 141
0

I think you are comparing two obect containers for equality - see this post... What's the fastest way to compare two arrays for equality? you need to compare the contents.

Community
  • 1
  • 1
Jay
  • 9,561
  • 7
  • 51
  • 72