The advantage of creating a list for ReadOnlyCollection or AsReadOnly

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

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

    instead:

     dinosaurs.AsReadOnly(); 
  • What is the real advantage of creating a list for ReadOnlyCollection or AsReadOnly?

+4
source share
4 answers

It makes no difference if you look at the AsReadOnly () code:

 public ReadOnlyCollection<T> AsReadOnly() { return new ReadOnlyCollection<T>(this); } 
+6
source

In general, they are the same as Erwin mentioned . There is one important case when they differ from each other. Because the AsReadOnly method is generic, the type of the newly created ReadOnlyCollection is inferred, not specified. Usually it just saves you from typing, but in the case of anonymous types, it really matters. If you have a list of anonymous objects, you need to use AsReadOnly , not new ReadOnlyCollection<ATypeThatHasNoName> .

+8
source

They are equivalent in functionality, but only because you start with List<T> .

The constructor form can be executed with any IList<T> , so in some cases this is the only option. The other form is a bit more concise, and with some mind (I would agree) it is a little better to describe what you are doing.

+2
source

You must use a read-only assembly if you want to ensure that no one can modify this collection. This, by the way, does not mean that the caller will not be able to modify the contents of this collection.

 var collection = List<object> {new SomeObject{...}, new SomeObject{..}}; //SOME OBJECT IS REFERENCE TYPE var readonly = new ReadOnlyCollection<string>(collection ); readonly[0].SomeObjectProperty = SomeValue; //HERE ORIGINAL OBJECT IS CHANGED 

As others have said, there is no difference between the two challenges present in the question.

0
source

All Articles