Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

List<T> implements IReadOnlyCollection<T> interface and provides the AsReadOnly() method which returns ReadOnlyCollection<T> (which in turn implements IReadOnlyCollection<T>).

What is the usage/reason for AsReadyOnly()? Its existence smells of one or two edge cases where just returning the list as IReadOnlyCollection<T> is just not good enough.

At first I though it may be to prevent casting the cost-ness away but it looks like you can do that with ReadOnlyCollection<T>'s Items accessor.

BTW. The documentation for ReadOnlyCollection<T> type reads

Provides the base class for a generic read-only collection.

which, in my head, conflicts with having a constructor described as

Initializes a new instance of the (...) class that is a read-only wrapper around the specified list.

Update: I did not see that ReadOnlyCollection<T>'s Items is protected.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
348 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you just return an actual List<T> as an IReadOnlyList<T>, then the caller can always just cast it back, and then modify the list as they please. Conversely, calling AsReadOnly() creates a read-only wrapper of the list, which consumers can't update.

Note that the read-only wrapper will reflect changes made to the underlying list, so code with access to the original list can still update it with the knowledge that any consumers of the read-only version will see those changes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...