Search code examples
c#.netlistreadonly-collection

How does List<T> copy constructor function with ReadOnly lists?


The MSDN article doesn't really explain this.

List<MyObject> FirstList = new List<MyObject>();
// Add items to FirstList.
List<MyObject> SecondList = new List<MyObject>(FirstList.AsReadOnly());
// Is SecondList a read-only collection?

Solution

  • No, the second list is not read-only, it's still a List generated from an IEnumerable<T> (specifically an ICollection<T> here). The .AsReadOnly() method just gives a ReadOnlyCollection<MyObject>, but we're not modifying that collection when messing with the second list.

    Instead, you've created a new List<MyObject> with its members that is editable (via the List<T>(IEnumerable<T>) constructor). This does the generation like any other IEnumerable<T> source that's an ICollection<T>, it performs a .CopyTo() underneath.

    In the case of a ReadOnlyCollection<T> (which implements ICollection<T>), it's calling .CopyTo() on the original IList<T> underneath that it was from, so basically what you have is the same as:

    List<MyObject> FirstList = new List<MyObject>();
    // Add items to FirstList.
    List<MyObject> SecondList = new List<MyObject>(FirstList);
    

    ....as far as the second list is concerned. In other cases where the IEnumerable<T> passed to the constructor is not a ICollection<T>, it would iterate over the collection and .Add() each member instead...but it would still have no impact on the mutability of the new list and its members.