Marcer
Marcer

Reputation: 849

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?

Upvotes: 6

Views: 5909

Answers (4)

Servy
Servy

Reputation: 203829

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

Upvotes: 10

Jon Hanna
Jon Hanna

Reputation: 113272

They're equivalent in functionality - but only because you're starting with a List<T>.

The constructor form can be done with any IList<T>, so is the only option in some cases. The other form is a tad more concise, and to some minds (I would agree) a bit nicer in describing just what you are doing.

Upvotes: 2

Erwin
Erwin

Reputation: 4817

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

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

Upvotes: 8

Tigran
Tigran

Reputation: 62246

You should use readonly collection in case when you want to guarantee that none can change that collection. Which is, by the way, doesn't mean that caller will not be able to change the content of that 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 said , there is no difference between those 2 calls present in the question.

Upvotes: -1

Related Questions