Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Specification - Section 1.6.7.5 can someone please explain this example? [duplicate]

Tags:

c#

I wanted to learn more about C# language and a lot of people have recommended digging into the C# specification, so I went and downloaded a copy of it from MSDN and started reading and going through the examples.

C# Specification Introducton - Section 1.6.7.5 Operators

"The List class declares two operators, operator == and operator !=, and thus gives new meaning to expressions that apply those operators to List instances. Specifically, the operators define equality of two List instances as comparing each of the contained objects using their Equals methods. The following example uses the == operator to compare two List instances."

I don't understand why the output would be True and False as opposed to both being False.

using System;
class Test
{
    static void Main() {
        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" 
        b.Add(3);
        Console.WriteLine(a == b);      // Outputs "False"
    }
}

I pop this into Visual Studio and sure enough I got both the Console.WriteLine() as 'False' as opposed to both being 'True' and 'False' as specified in the comments.

It also states that the List-of-T declares a single event member called Changed, I could not for the life of me find it, I went into the decompiler and had a look as well.

Maybe I'm completely mis-reading it or I've got the wrong C# specification.

like image 731
TheLazyChap Avatar asked Oct 05 '13 15:10

TheLazyChap


2 Answers

That passage does not refer to System.Collections.Generic.List<T>, but rather to a hypothetical List<T> class that appears in section 1.6.7:

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

That class List does overload operators == and != to work as shown, has a Changed event etc.

like image 106
Jon Avatar answered Oct 18 '22 07:10

Jon


List<T> does not provide a == operator, so it defaults to that from object which is referential equality. You see the result false each time (and every time) because those two lists are not the same instances, and never will be.

like image 34
Darren Kopp Avatar answered Oct 18 '22 08:10

Darren Kopp