简体   繁体   中英

When is a List(T) collection “modified”?

According to the documentation of the List(T) class http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx a collection supports multiple readers. As long as the collection is not modified.

My question is when is a collection modified?

  • When I change a value in the list? For example a List<int> , intList[0] = 1;
  • When I add/delete something of the list? For example, intList.add(1);

Thanks for your help.

Paul

For a list, it counts as modified when you add or remove elements from the array OR you change the contents of an element, so both your examples do indeed "modify" the collection.

But as a sidenote: For an array, you effectively cannot "modify" the collection, in this context.

So we have a clear difference in behaviour between List<T> and a plain array of T.

For example, this code throws an exception:

var testList = Enumerable.Range(1, 10).ToList();

foreach (var i in testList)
{
    testList[0] = 1;
}

But this code does not throw an exception:

var testArray = Enumerable.Range(1, 10).ToArray();

foreach (var i in testArray)
{
    testArray[0] = 1;
}

Changing a property of a reference type stored in an element

Note that if you have a list of a reference type, and you change one of the properties of one of the list's elements, that does not count as modifying the collection.

So for example, given this class:

class Element
{
    public int Value
    {
        get;
        set;
    }
}

The following code does NOT throw an exception:

List<Element> list = new List<Element>()
{
    new Element(),
    new Element()
};

foreach (var element in list)
{
    list[0].Value = 1;
}

The reason it doesn't count as modifying the collection is that you are not changing the contents of an element, since the reference itself remains exactly the same.

My question is when is a collection modified?

When I change a value in the list? For example a List<int>, intList[0] = 1;

Yes, changing the item does change the collection.

However, when your T from List<T> is a reference type, and you don't change the entire object (eg change only one class property value) the collection is not modified. eg consider a class Foo with int property Bar .

List<Foo> items = new List<Foo> { new Foo(), new Foo() };

Following code does modify the collection:

items[0] = new Foo();

And following does not modify the collection:

items[0].Bar = 10;

When I add/delete something of the list? For example, intList.add(1);

It always modifies the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM