7

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.

Marcel Gosselin
  • 4,550
  • 2
  • 27
  • 51
Alex Marshall
  • 9,856
  • 13
  • 69
  • 114

1 Answers1

19

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
  • 93,968
  • 29
  • 116
  • 128
  • 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
  • 3
    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 Nov 10 '09 at 20:23
  • 7
    The last line can be `var readonlyDinosaurs = dinosaurs.AsReadOnly()` – Ruben Bartelink Nov 10 '09 at 20:30
  • 8
    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 Nov 10 '09 at 21:25