Yesterday I asked a question about deep cloning a list and I got a wonderful answer, which you can read here.
The issue I have is the answer uses ImmutableList
and I've got no issue with it, it's just that if I wanted to use ReadOnlyCollection and ensure that I return a copy of my collection and that the one in the class cannot be modified.
I just wanted to know if the following is correct.
private ReadOnlyCollection<Author> listofAuthors;
private List<Author> copyofAuthors;
public Book(ICollection<Author> authors)
{
copyofAuthors = new List<Author>(authors);
listofAuthors = new ReadOnlyCollection<Author>(new List<Author>(copyofAuthors));
}
public ICollection<Author> Authors
{
get
{
return new ReadOnlyCollection<Author>(new List<Author>(copyofAuthors));
}
}
According to MSDN documentation ReadOnlyCollection
is just a wrapper for a underly mutable collection. So if any changes are made to the underlying collection it would be reflected in the ReadOnlyCollection
. The above code the getter returns a new List as a readonly collection.
Question 1:
Given the above code, any other code calling it will get a copy of the private ReadOnly(new List()), correct? Any changes that the user makes will not be reflected in the ReadOnlyCollection inside the Book class, right?
Question 2:
I understand ImmutableList
is more ideal, but if I needed to use ReadOnlyCollection<Authors>
is what I've done in the Constructor/Getter correct? or can it be implemented in another/better way?