I have a list, and I want to provide read-only access to a collection containing its contents. How can I do this?
Something like:
public ICollection<Foo> ImmutableViewOfInventory() {
IList<Foo> inventory = new List<Foo>();
inventory.add(new Foo());
return inventory.ImmutableView();
}
Additionally, an immutable IEnumerable
would also be fine.
UPDATE: I realize now that an immutable view of the list would actually be better. (Preserving list ordering semantics.)
This won't give me list behavior, right:
public ReadOnlyCollection<PickUp> InventoryItems()
{
return new ReadOnlyCollection<PickUp>(inventory);
}
I'm looking in the documentation but not immediately seeing ReadOnlyList<T>
.
If you are wanting an immutable list of the items, you can return a ReadOnlyCollection by calling the AsReadOnly() method on your list:
public IList<Foo> ImmutableViewOfInventory()
{
List<Foo> inventory = new List<Foo>();
inventory.Add(new Foo());
return inventory.AsReadOnly();
}
This returns an implementation of IList
that is both strongly-typed and not modifiable.
It does not however prevent changes to any of the items contained in the list (unless they are value types). To do that, each item must be cloned (deep-cloned if they themselves contain other objects) and added to a new read only list that is returned from your ImmutableViewOfInventory
method. You will have to implement this yourself unfortunately.
Have you looked at ReadOnlyCollection<T>?
http://msdn.microsoft.com/en-us/library/ms132474.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With