Reputation:
Dotnet 4.5 has introduce ReadOnlyCollection. My question is what is the practical useage of it? What scenarios we may need this kind of data structure?
Upvotes: 0
Views: 97
Reputation: 2195
This class is useful in a multithreading application. In a multithreading environment can it be a real problem to have a collection of objects, which might be changed by some other thread. This assures threadsafety and lessens the complexity of the code.
Upvotes: 0
Reputation: 180944
When you want to return a collection that the caller should not be able to modify, but you still want to have the guarantees that an IList
gives over an IEnumerable
, e.g. a free .Count property, an indexer and the ability to safely iterate over it multiple times, both which aren't guaranteed on an IEnumerable
.
Upvotes: 1
Reputation: 726599
You need read-only collections when your API returns collection objects to your callers, copying is too expensive, and you would prefer to stay away from returning IEnumerable<T>
. This is commonly desirable in situations when random access is required over the returned collection.
Upvotes: 1