OneBite.Dev - Coding blog in a bite size

Check If Two Arrays Are Equal In C#

Code snippet for how to Check If Two Arrays Are Equal In C# with sample and detail explanation

Comparing arrays to check if they are identical might be a common task you encounter while programming in C#. It involves confirming if two different arrays have the same number of elements and if those elements have identical values.

Code snippet for Comparing Two Arrays

public static bool TwoArraysAreEqual(int[] array1, int[] array2)
{
    if (array1.Length != array2.Length)
        return false;
    for (var i = 0; i < array1.Length; i++)
        if (array1[i] != array2[i])
            return false;
    return true;
}

public static void Main()
{
    var array1 = new[] { 1, 2, 3, 4, 5 };
    var array2 = new[] { 1, 2, 3, 4, 5 };
    var result = TwoArraysAreEqual(array1, array2);
    
    Console.WriteLine(result ? "Arrays are equal." : "Arrays are not equal.");
}

Code Explanation for Comparing Two Arrays

In the above C# code snippet, function TwoArraysAreEqual takes in two integer arrays as arguments.

The first thing checked is whether the lengths of the two arrays are equal. If they are not, the function immediately returns false cause two arrays can’t be equal if they have different lengths.

Next, the program enters a loop that goes from the first to the last element of the arrays. If ever it finds that an element in the first array doesn’t match the corresponding one in the second array, it immediately returns false. This check is thorough, examining every single element to ensure complete equality.

Then, after having compared the lengths of the arrays and the individual elements, if the function hasn’t yet returned false, it returns true. This signals that the two arrays are equal, as they’ve passed all the necessary checks.

Lastly, the Test() function uses two test arrays and then invokes the TwoArraysAreEqual function with them. It will then print out the result. If the arrays are identical, “Arrays are equal” will be printed; if not, “Arrays are not equal” will be outputted.

It’s important to remember that this function checks for equality, not similarity. The arrays must have the same elements in the same order to be considered equal. If the same elements are present, but in a different order, this check will fail, and the function will return false.

c-sharp