Reputation: 849
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Why should I use a ReadOnlyCollection
as follows:
var readOnlyDinosaurs = new ReadOnlyCollection<string>(dinosaurs);
instead of:
dinosaurs.AsReadOnly();
What is the real advantage of making a List to a ReadOnlyCollection or a AsReadOnly?
Upvotes: 6
Views: 5909
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
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
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
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