Read-only list or unmodifiable list in .NET 4.0

You're looking for ReadOnlyCollection, which has been around since .NET2.

IList<string> foo = ...;
// ...
ReadOnlyCollection<string> bar = new ReadOnlyCollection<string>(foo);

or

List<string> foo = ...;
// ...
ReadOnlyCollection<string> bar = foo.AsReadOnly();

This creates a read-only view, which reflects changes made to the wrapped collection.


For those who like to use interfaces: .NET 4.5 adds the generic IReadOnlyList interface which is implemented by List<T> for example.

It is similar to IReadOnlyCollection and adds an Item indexer property.


How about the ReadOnlyCollection already within the framework?