Every time I create an object that has a collection property I go back and forth on the best way to do it?
- public property with a getter that returns a reference to private variable
- explicit get_ObjList and set_ObjList methods that return and create new or cloned objects every time
- explicit get_ObjList that returns an IEnumerator and a set_ObjList that takes IEnumerator
Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?
If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?
And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?
The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has enumeration concerns
Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.
Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?