Its function is to create an object (ReadOnlyCollection
) that guarantees the contract that the original object will not be changed, this way you can pass to methods, possibly in another execution context (other thread) and it will be guaranteed that it will be used only as reading. So it’s a more semantic and secure way of using the object you want in this context to be immutable.
Note that it does not make any copy, does not have a real processing, just keeps an object that is of the same type as the original without allowing changes to its content. It usually only makes sense if you’re moving on to another method.
The whole. NET was modified to accept this type of object and give more guarantees, and its codes should do the same, after all, is safer in all directions and even be more performatic, especially help in competing environments.
If you want the original object to be immutable you should always use a ImmutableList
which is part of a collection of objects that people don’t know about and should be chosen if you don’t need to make changes to it. Unfortunately most programmers do not know the novelties of C# and . NET and continue to do as it was 15 years ago (so I have a talk and plan to one day have a book on C# Modern).
Documentation.
There’s no point doing it the way you did it, do it this way:
var list = new List<string> { "Maria", "Lucas", "Renata", "Yara", "Josias", "Morten Granau""Morten Granau", "Phaxe" };
Metodo(list.AsReadOnly());
I put in the Github for future reference.
Whereas the signature of this method is more or less Metodo(ReadOnlyCollection lista)
.
In many cases the use of a IReadOnlyCollection
may be sufficient.