Occasionally, we want to determine whether two array variables are equal to each other. We might attempt to answer this question by using the equality operator (==) as in the following:
int  myArray = new int ; int  yourArray = new int ; if (myArray == yourArray) Console.WriteLine("myArray is equal to yourArray");
But how does the equality operator == of C# compare two array variables (as in line 3 of the code sample) containing references to array objects? There are two possible options reference equality, where the references of the two array variables are compared, and value equality, where the array elements of the referenced array objects are compared. Let's have a closer look at each option before revealing which one the == operator of C# applies:
Reference equality If values of a reference type, such as System.Array, are compared for reference equality, the references held by the two variables are compared. If they are identical, meaning if they reference the same object (see the upper part of Figure 10.7), the comparison is true. If they reference different objects, even if those objects are of similar length and contain matching pairs of array elements holding identical values, the comparison is false (see the lower part of Figure 10.7).
Value equality If two array variables are compared for value equality, the array elements of the referenced array objects are compared with each other. Thus, the length of each array must be identical, and each matching pair of array elements must have identical values for this comparison to be true. The upper part of Figure 10.8 represents two arrays that are (value) equal because the two referenced array objects are of identical length and contain identical sets of array elements. In the lower part of Figure 10.8, myArray has had a few of its array elements changed and does not match the corresponding array elements in yourArray anymore. As a result, the two arrays here are not (value) equal.
The equals comparison operator (==) of C# supports reference equality between array variables. The implications are illustrated with the following source code:
Instead of performing reference equality comparisons by using the == operator, you might want to compare two arrays for value equality instead. One way to accomplish this task is by writing a method specialized in comparing two arbitrary arrays for value equality. The next section looks at how arrays and methods can cooperate and provides an understanding of how an array-comparing method can be written, along with a specific source code example.
Whereas the equals operator (==) compares for reference equality when applied to array variables, recall that it supports value equality when values of type string are compared (see Chapter 7, "Types Part II: Operators, Enumerators and Strings."