8

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,610
  • 2
  • 31
  • 54
Alex Marshall
  • 10,162
  • 15
  • 72
  • 117

1 Answers1

21

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
  • 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
  • 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