views:

455

answers:

5

From what I can tell, .NET 4.0 still lacks readonly lists. Can anyone shed light on why the framework still lacks this functionality? Isn't this one of the commonest pieces of functionality for domain drive 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 or List.

+1  A: 

In 2.0 you can call AsReadOnly to get a read-only version of the list. Or wrap an existing IList in a ReadOnlyCollection object.

Paul Alexander
Beat me to it!!!!!!!!
Jason Watts
that's the equivalent of Collections.unmodifiablelist(list) I was after
Chris S
+6  A: 

How about ReadOnlyCollection already within the framework?

Jason Watts
+14  A: 

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

List<string> foo = new List<string>();
// ...
ReadOnlyCollection<string> bar = foo.AsReadOnly();
LukeH
I feel a bit stupid having asked this question now - and not known about ReadOnlyCollection
Chris S
+1  A: 

If the most common pattern of the list is to iterate through all elements, IEnumerable or IQueryable can effectively act as a read-only list as well.

Paul Betts
If you expose your List as an IEnumerable, then the consumer could simply cast it back to List and modify it.
JulianR
Of course, but it's not intended to be a bulletproof measure - you could also probably read the private fields and track down the original list. It's more as describing the intent that this should stay read-only.
Paul Betts
+2  A: 

What's wrong with System.Collections.ObjectModel.ReadOnlyCollection?

mdresser