Alex Rivera | Logout

List<T> operator == In the C# Language Specification Version 4

Asked 2012-08-07T19:16:49.830
22

In the C# Language Specification Version 4, 1.6.7.5 Operators is information about List<T> operators: == and !=. But I can't find such operators defined in List<T>? Am I missing something?

Sample code from 1.6.7.5 Operators:

List<int> a = new List<int>();
a.Add(1);
a.Add(2);
List<int> b = new List<int>();
b.Add(1);
b.Add(2);
Console.WriteLine(a == b); // Outputs "True" => here I get False as well
b.Add(3);
Console.WriteLine(a == b); // Outputs "False"
Edit
Report

1 Answer

18

The spec is indeed correct, although confusing. The spec defines a class called List (poor naming choice).

The following table shows a generic class called List, which implements a growable list of objects. The class contains several examples of the most common kinds of function members.

This class can be seen in the spec at section 1.6.7. The Equals operator is overloaded and matches the output explained above. Perhaps a better name should have been chosen for that class.

static bool Equals(List<T> a, List<T> b) {
    if (a == null) return b == null;
    if (b == null || a.count != b.count) return false;
    for (int i = 0; i < a.count; i++) {
        if (!object.Equals(a.items[i], b.items[i])) {
            return false;
        }
    }
  return true;
}
answered 2012-08-07T19:37:30.110

Your Answer