Arrays and Equality

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 [6];
int [] yourArray = new int [6];

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 ...

Get C# Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.