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.
Asked
Active
Viewed 5,736 times
8

Marcel Gosselin
- 4,610
- 2
- 31
- 54

Alex Marshall
- 10,162
- 15
- 72
- 117
-
There are quite a few questions covering this, including: http://stackoverflow.com/questions/1326574/properly-exposing-a-listt – Ruben Bartelink Nov 10 '09 at 20:29
-
Net framework offers that http://stackoverflow.com/questions/984042/unmodifiablelist-in-net-4-0 – Captain Comic Nov 10 '09 at 20:21
1 Answers
21
var dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
var readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);

Bob
- 97,670
- 29
- 122
- 130
-
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 Nov 10 '09 at 20:22
-
3The 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 Nov 10 '09 at 20:23
-
7The last line can be `var readonlyDinosaurs = dinosaurs.AsReadOnly()` – Ruben Bartelink Nov 10 '09 at 20:30
-
8Note 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 Nov 10 '09 at 21:25