First off, if you have two questions then post two questions. I'll answer your first question.
Second, good for you for thinking about how to protect your list from mutation. A lot of people forget about this and expose their internal state to callers.
There are a number of things you can do.
1) Don't use a mutable list in the first place. Use an immutable list. The Add
method of an immutable list returns a different list rather than mutating the current list. There are new immutable list classes in the BCL now. These can be very efficient in both space and time.
2) Use a mutable list and make a copy every time. You're already doing this. The problem is of course that it is slow and uses a lot of memory.
3) Return AsReadOnly
as Claudio suggests. Note that this just makes a read-only façade around the list; if the list changes, the read-only façade changes too. "Read only" means just that: the user cannot write it. It does not mean that it never changes. Also, there's an enumeration issue, which I'll address in (4):
4) Make LINQ do the work. return _myCollection.Select(x=>x);
and have the property be of type IEnumerable<int>
. This has two downsides. First, the caller only gets forward enumeration. Second, suppose the caller is doing a foreach
over the property, and then inside the loop does something which changes the list. This will cause an exception; you can't change a list while you're enumerating it. If you need to support that scenario then (1) or (2) are your best bet; in those the enumeration will be over a snapshot, not over the mutating list.