Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to expose a collection property?
    primarykey
    data
    text
    <p>Every time I create an object that has a collection property I go back and forth on the best way to do it?</p> <ol> <li>public property with a getter that returns a reference to private variable</li> <li>explicit get_ObjList and set_ObjList methods that return and create new or cloned objects every time</li> <li>explicit get_ObjList that returns an IEnumerator and a set_ObjList that takes IEnumerator</li> </ol> <p>Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?</p> <p>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?</p> <p>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?</p> <p>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 <a href="http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx" rel="noreferrer">enumeration concerns</a> </p> <p>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.</p> <p>Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload