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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, the second list is not read-only, it’s still a List generated from an
IEnumerable<T>(specifically anICollection<T>here). The.AsReadOnly()method just gives aReadOnlyCollection<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 theList<T>(IEnumerable<T>)constructor). This does the generation like any otherIEnumerable<T>source that’s anICollection<T>, it performs a.CopyTo()underneath.In the case of a
ReadOnlyCollection<T>(which implementsICollection<T>), it’s calling.CopyTo()on the originalIList<T>underneath that it was from, so basically what you have is the same as:….as far as the second list is concerned. In other cases where the
IEnumerable<T>passed to the constructor is not aICollection<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.