views:

307

answers:

3

In Java, one can use the Collections#unmodifiableList() method to create an unmodifiable list from an existing List object. Is there any counterpart in C# ? I'm new to the language and haven't been able to find anything like this in the MSDN docs.

+11  A: 

ReadOnlyCollection

var dinosaurs = new List<string>();

dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

var readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);
Bob
Exactly what I'm looking for, thank you. I guess I haven't gotten used to how to search the MSDN site yet.
Alex Marshall
The best search for MSDN is google :) But I knew it was called ReadOnlyCollection, If you are searching for Unmodifiable list you might have less results.
Bob
The last line can be `var readonlyDinosaurs = dinosaurs.AsReadOnly()`
Ruben Bartelink
Note that this does not actually make the collection itself read-only. Rather, it gives you a read-only wrapper around the mutable collection; attempts to mutate the wrapper will throw exceptions, but anyone who can get a reference to the original collection can still mutate it.
Eric Lippert
+2  A: 

Net framework offers that http://stackoverflow.com/questions/984042/unmodifiablelist-in-net-4-0

Captain Comic
A: 

There are quite a few questions covering this, including: http://stackoverflow.com/questions/1326574/properly-exposing-a-listt

Ruben Bartelink