Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of making a List to a ReadOnlyCollection or AsReadOnly

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
  1. Why should I use a ReadOnlyCollection as follows:

    var readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);
    

    instead of:

    dinosaurs.AsReadOnly();
    
  2. What is the real advantage of making a List to a ReadOnlyCollection or a AsReadOnly?

like image 404
John Avatar asked Aug 29 '12 19:08

John


People also ask

What is IReadOnlyCollection?

The IReadOnlyCollection interface extends the IEnumerable interface and represents a basic read-only collection interface. It also includes a Count property apart from the IEnumerable members as shown in the code snippet given below.

Can you add items to a readonly list C#?

In C# there is the readonly keyword that enforced the rule that the variable must be initialised as it's declared or in the constructor. This works as expected for simple types, but for objects and lists it's not quite like that. With a list, you can still add, remove and change items in the list.


2 Answers

In general, they are the same, as mentioned by Erwin. There is one important case where they differ though. Because the AsReadOnly method is generic, the type of the newly created ReadOnlyCollection is infered, not specifically listed. Normally this just saves you a bit of typing, but in the case of anonymous types it actually matters. If you have a list of anonymous objects you need to use AsReadOnly, rather than new ReadOnlyCollection<ATypeThatHasNoName>.

like image 101
Servy Avatar answered Sep 21 '22 20:09

Servy


There is no difference, if you look at the code of AsReadOnly():

public ReadOnlyCollection<T> AsReadOnly()
{
    return new ReadOnlyCollection<T>(this);
}
like image 30
Erwin Avatar answered Sep 20 '22 20:09

Erwin