Yes, I know that this has been discussed many times before, and I read all the posts and comments on this subject, but still can not understand something.
One of the options that MSDN offers to solve this violation is to return the collection (or the interface that the collection implements) when accessing the property, however, this obviously does not solve the problem, because most collections are not immutable and can also be changed.
Another possibility that I saw in the answers and comments on this question is to encapsulate the array using ReadOnlyCollection and return it or the base interface (e.g. IReadOnlyCollection), but I don't understand how this solves the performance issue.
If at any time it refers to a property, it needs to allocate memory for a new ReadOnlyCollection that encapsulates the array, so what is the difference (in the form of performance problems, and not for editing an array / collection) than just returning a copy of the original array?
In addition, ReadOnlyCollection has only one constructor with an IList argument, so you need to wrap an array with a list before creating it.
If I intentionally want to work with an array inside my class (not as an immutable collection), is performance better when I allocate new memory for ReadOnlyCollection and encapsulate my array with it instead of returning a copy of the array?
Please clarify this ...
source share