view raw
Chris S Chris S - 10 months ago 52
Java Question

Read-only list or unmodifiable list in .NET 4.0

From what I can tell, .NET 4.0 still lacks read-only lists. Why does the framework still lack this functionality? Isn't this one of the commonest pieces of functionality for domain-driven design?

One of the few advantages Java has over C# is this in the form of the Collections.unmodifiablelist(list) method, which it seems is long overdue in IList<T> or List<T>.


is the easiest solution to the question -
can be used and returns a copy.


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

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


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

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