Reputation: 5884
Is there any class in .net
which works like IReadOnlyList
but it holds internal copy of all items? If something returns IReadOnlyList
, there is no guarantee that underlying collection will no be modified?...
EDIT:
From documentation:
An instance of the
ReadOnlyCollection<T>
generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection == reflects == those changes
So it's not true read only.
EDIT2:
I need something like read-only array.
For example:
public class ReadOnlyArray<T> : IEnumerable<T>, ...
{
public ReadOnlyArray (IEnumerable<T> items)
{
internalItems = createCopy (items);
}
}
now when I see code like this: ReadOnlyArray x = GetDataFrom3rdAPI();
I'm 100% I am not only receiving read-only object, but also it is not possible to modify underlying collection somewhere else in code. The class type should say it gives me that comfort.
With ReadOnlyCollection, it says only I can read, but I have no control over underyling collection - I dont know is there any reference to underlying collection in other places in 3rd API code.
EDIT3:
When I said underlying collection should not be modified, I had on my mind that all items in collection (all references) should always point to the same instance. However those instances itself can be mutable.
So when Im iterating through this collection, I'm always iterating the same instances.
Upvotes: 0
Views: 496
Reputation: 4249
With a ReadOnlyCollection collection, you are sure that client code cannot modify the collection, i.e add or remove elements from the collection. But client code can still modify the items contained in your collection:
myReadOnlyCollection.Add(new Object())// error, cannot add/remove items to readonlyCollection
MyObjet obj = myReadOnlyCollection[3] // get the 3rd item in the collection, ok;
obj.someProperty = 9; // ops, the object contained in the ReadOnlyCollection has been changed!
You have two different problems to face:
Upvotes: 0
Reputation: 898
Given any IEnumerable<T> foo
, use foo.ToList().AsReadOnly()
. This will make a new List<T>
containing the elements of foo
, even if was already a list, and then make a read-only wrapper around that list. As the underlying collection for the ReadOnlyCollection<T>
is the one you just created, nothing else will have a reference to it and so nothing else will be able to change it (save reflection tomfoolery).
Upvotes: 3