2

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?
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Giffyguy
  • 20,378
  • 34
  • 97
  • 168

1 Answers1

7

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155