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?
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.
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.
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>
.
There is no difference, if you look at the code of AsReadOnly():
public ReadOnlyCollection<T> AsReadOnly()
{
return new ReadOnlyCollection<T>(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With