tags:

views:

203

answers:

3

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>.

+1  A: 

Have you looked at ReadOnlyCollection{T}?

http://msdn.microsoft.com/en-us/library/ms132474.aspx

Ari Roth
A: 

new ReadOnlyCollection(inventory);

MikeP
+2  A: 

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.

adrianbanks
For some reason I can't `inventory.AsReadOnly()` to compile, even though I've imported `System.Collections.Generic`. It says that the method doesn't exist.
Rosarch
Actually, that's because I was using an `IList` instead of a `List`. Why isn't it available on `IList`?
Rosarch