Let’s say I have a private dictionary or a list in my class. I want to return a readonly enumerator so that others can iterate over the list, but not have access to modify the items.
Instead of creating a wrapper class around the original, I’d like to return copies of the original items/elements. Will something like original.ToList<Type>().GetEnumerator() return a list with references to the original items, or a list with copies of the original items?
I should note that I also need indexing (i.e. accessing items by index, still not being able to modify them).
The methods create a new instance of the collection, but the item references will still be to the old items. In other words, a consumer could not update your internal collection, but they could update the items themselves.
Assuming you have appropriate encapsulation around modifying the items, this approach will work, though it is a little memory-intensive for larger lists, since you need to allocate memory for each new item reference. That’s one reason why returning a wrapper is often preferred: it reduces the extra memory required to a single instance of the wrapper class.