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>.
Using IEnumerable<T>
is the easiest solution to the question - ToList
can be used and returns a copy.
You're looking for
ReadOnlyCollection
, which has been around since .NET2.or
This creates a read-only view, which reflects changes made to the wrapped collection.
If the most common pattern of the list is to iterate through all the elements,
IEnumerable<T>
orIQueryable<T>
can effectively act as a read-only list as well.What's wrong with System.Collections.ObjectModel.ReadOnlyCollection?
In 2.0 you can call
AsReadOnly
to get a read-only version of the list. Or wrap an existingIList
in aReadOnlyCollection<T>
object.How about the ReadOnlyCollection already within the framework?
For those who like to use interfaces: .NET 4.5 adds the generic
IReadOnlyList
interface which is implemented byList<T>
for example.It is similar to
IReadOnlyCollection
and adds anItem
indexer property.