<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>

[{'answer_id': 35018, 'author': 'Ryan Duffield', 'author_id': 2696, 'author_profile': 'https://Stackoverflow.com/users/2696', 'pm_score': 0, 'selected': False, 'text': "<p>If you're simply looking to expose a collection on your instance, then using a getter/setter to a private member variable seems like the most sensible solution to me (your first proposed option).</p>\n"}, {'answer_id': 35065, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 2, 'selected': False, 'text': '<p>I usually go for this, a public getter that returns System.Collections.ObjectModel.ReadOnlyCollection:</p>\n\n<pre><code>public ReadOnlyCollection&lt;SomeClass&gt; Collection\n{\n    get\n    {\n         return new ReadOnlyCollection&lt;SomeClass&gt;(myList);\n    }\n}\n</code></pre>\n\n<p>And public methods on the object to modify the collection.</p>\n\n<pre><code>Clear();\nAdd(SomeClass class);\n</code></pre>\n\n<p>If the class is supposed to be a repository for other people to mess with then I just expose the private variable as per method #1 as it saves writing your own API, but I tend to shy away from that in production code.</p>\n'}, {'answer_id': 35154, 'author': 'Telcontar', 'author_id': 518, 'author_profile': 'https://Stackoverflow.com/users/518', 'pm_score': 0, 'selected': False, 'text': "<p>I'm a java developer but I think this is the same for c#.</p>\n\n<p>I never expose a private collection property because other parts of the program can change it without parent noticing, so that in the getter method I return an array with the objects of the collection and in the setter method I call a <code>clearAll()</code> over the collection and then an <code>addAll()</code></p>\n"}, {'answer_id': 38410, 'author': 'Emperor XLII', 'author_id': 2495, 'author_profile': 'https://Stackoverflow.com/users/2495', 'pm_score': 7, 'selected': True, 'text': '<p>How you expose a collection depends entirely on how users are intended to interact with it.</p>\n\n<p><strong>1)</strong> If users will be adding and removing items from an object\'s collection, then a simple get-only collection property is best (option #1 from the original question):</p>\n\n<pre><code>private readonly Collection&lt;T&gt; myCollection_ = new ...;\npublic Collection&lt;T&gt; MyCollection {\n  get { return this.myCollection_; }\n}\n</code></pre>\n\n<p>This strategy is used for the <code>Items</code> collections on the WindowsForms and WPF <code>ItemsControl</code> controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items.</p>\n\n<p>WPF also exposes some settable collections to allow users to display a collection of items they control, such as the <code>ItemsSource</code> property on <code>ItemsControl</code> (option #3 from the original question). However, this is not a common use case.</p>\n\n<p><br/>\n<strong>2)</strong> If users will only be reading data maintained by the object, then you can use a readonly collection, as <a href="https://stackoverflow.com/questions/35007/how-to-expose-a-collection-property#35065">Quibblesome</a> suggested:</p>\n\n<pre><code>private readonly List&lt;T&gt; myPrivateCollection_ = new ...;\nprivate ReadOnlyCollection&lt;T&gt; myPrivateCollectionView_;\npublic ReadOnlyCollection&lt;T&gt; MyCollection {\n  get {\n    if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ }\n    return this.myPrivateCollectionView_;\n  }\n}\n</code></pre>\n\n<p>Note that <code>ReadOnlyCollection&lt;T&gt;</code> provides a live view of the underlying collection, so you only need to create the view once.</p>\n\n<p>If the internal collection does not implement <code>IList&lt;T&gt;</code>, or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator:</p>\n\n<pre><code>public IEnumerable&lt;T&gt; MyCollection {\n  get {\n    foreach( T item in this.myPrivateCollection_ )\n      yield return item;\n  }\n}\n</code></pre>\n\n<p>This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection.</p>\n\n<p><br/>\n<strong>3)</strong> Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question):</p>\n\n<pre><code>private T[] myArray_;\npublic T[] GetMyArray( ) {\n  T[] copy = new T[this.myArray_.Length];\n  this.myArray_.CopyTo( copy, 0 );\n  return copy;\n  // Note: if you are using LINQ, calling the \'ToArray( )\' \n  //  extension method will create a copy for you.\n}\n</code></pre>\n\n<p>You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding <code>SetMyArray( T[] array )</code> method, or use a custom indexer:</p>\n\n<pre><code>public T this[int index] {\n  get { return this.myArray_[index]; }\n  set {\n    // TODO: validate new value; raise change event; etc.\n    this.myArray_[index] = value;\n  }\n}\n</code></pre>\n\n<p>(of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :)</p>\n'}, {'answer_id': 1235566, 'author': 'jpierson', 'author_id': 83658, 'author_profile': 'https://Stackoverflow.com/users/83658', 'pm_score': 0, 'selected': False, 'text': '<p>Why do you suggest using ReadOnlyCollection(T) is a compromise? If you still need to get change notifications made on the original wrapped IList you could also use a <a href="http://msdn.microsoft.com/en-us/library/ms668620.aspx" rel="nofollow noreferrer">ReadOnlyObservableCollection(T)</a> to wrap your collection. Would this be less of a compromise in your scenario?</p>\n'}, {'answer_id': 30313404, 'author': 'Johannes', 'author_id': 48621, 'author_profile': 'https://Stackoverflow.com/users/48621', 'pm_score': 1, 'selected': False, 'text': '<p>ReadOnlyCollection still has the disadvantage that the consumer can\'t be sure that the original collection won\'t be changed at an inopportune time. Instead you can use <a href="https://msdn.microsoft.com/en-us/library/dn769092%28v=vs.111%29.aspx" rel="nofollow">Immutable Collections</a>. If you need to do a change then instead changing the original you are being given a modified copy. The way it is implemented it is competitive with the performance of the mutable collections. Or even better if you don\'t have to copy the original several times to make a number of different (incompatible) changes afterwards to each copy.</p>\n'}, {'answer_id': 32914905, 'author': 'jbe', 'author_id': 103988, 'author_profile': 'https://Stackoverflow.com/users/103988', 'pm_score': 1, 'selected': False, 'text': '<p>I recommend to use the new <code>IReadOnlyList&lt;T&gt;</code> and <code>IReadOnlyCollection&lt;T&gt;</code> Interfaces to expose a collection (requires .NET 4.5).</p>\n\n<p><em>Example:</em></p>\n\n<pre><code>public class AddressBook\n{\n    private readonly List&lt;Contact&gt; contacts;\n\n    public AddressBook()\n    {\n        this.contacts = new List&lt;Contact&gt;();\n    }\n\n    public IReadOnlyList&lt;Contact&gt; Contacts { get { return contacts; } }\n\n    public void AddContact(Contact contact)\n    {\n        contacts.Add(contact);\n    }\n\n    public void RemoveContact(Contact contact)\n    {\n        contacts.Remove(contact);\n    }\n}\n</code></pre>\n\n<p>If you need to guarantee that the collection can not be manipulated from outside then consider <code>ReadOnlyCollection&lt;T&gt;</code> or the new Immutable collections.</p>\n\n<p><strong>Avoid</strong> using the interface <code>IEnumerable&lt;T&gt;</code> to expose a collection.\nThis interface does not define any guarantee that multiple enumerations perform well. If the IEnumerable represents a query then every enumeration execute the query again. Developers that get an instance of IEnumerable do not know if it represents a collection or a query.</p>\n\n<p>More about this topic can be read on this <a href="https://github.com/jbe2277/waf/wiki/How-should-a-class-expose-a-collection%3F" rel="nofollow">Wiki page</a>.</p>\n'}]
['https://Stackoverflow.com/questions/35007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2582/']