Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Immutable view of a list's objects?

Tags:

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

like image 954
Nick Heiner Avatar asked Apr 15 '10 23:04

Nick Heiner


Video Answer


2 Answers

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.

like image 185
adrianbanks Avatar answered Sep 24 '22 22:09

adrianbanks


Have you looked at ReadOnlyCollection<T>?

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

like image 26
Ari Roth Avatar answered Sep 23 '22 22:09

Ari Roth