Search code examples
c#.netcollectionsc#-4.0unmodifiable

Unmodifiable lists in C#


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.


Solution

  • ReadOnlyCollection

    var dinosaurs = new List<string>();
    
    dinosaurs.Add("Tyrannosaurus");
    dinosaurs.Add("Amargasaurus");
    dinosaurs.Add("Deinonychus");
    dinosaurs.Add("Compsognathus");
    
    var readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);