user544079
user544079

Reputation: 16629

Comparing arrays in c# based on user input

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

Upvotes: 0

Views: 1048

Answers (4)

Steve
Steve

Reputation: 216273

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");

Upvotes: 0

Anthony
Anthony

Reputation: 510

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

Upvotes: 3

Jay
Jay

Reputation: 10118

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.

Upvotes: 0

epitka
epitka

Reputation: 17627

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

Upvotes: 0

Related Questions