Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can make your property return a wrapper around the original list using <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx" rel="nofollow noreferrer"><code>ReadOnlyCollection&lt;T&gt;</code></a>. This will ensure that callers don't add any items themselves. You can keep a reference to the original mutable list. Note that because the read-only collection is only a wrapper, callers which cache the read-only collection will still see additions that you make to the original list. That may or may not be a good thing depending on your expected use.</p> <p>EDIT: To explain my caching comment...</p> <p>Suppose a client did:</p> <pre><code>IList&lt;ChildObject&gt; originalChildren = container.Children; container.AddChild(new ChildObject()); IList&lt;ChildObject&gt; updatedChildren = container.Children; </code></pre> <p>with the <code>Children</code> property implemented like this:</p> <pre><code>private IList&lt;ChildObject&gt; children = new List&lt;ChildObject&gt;(); public IList&lt;ChildObject&gt; Children { get { return new ReadOnlyCollection&lt;ChildObject&gt;(children); } } </code></pre> <p>Then <code>originalChildren</code> and <code>updateChildren</code> would both have the same contents - the returned <code>ReadOnlyCollection</code> wouldn't be a <em>snapshot</em> of the collection of children at the first line. It would just be a <em>wrapper</em> around the collection. Clients wouldn't be able to rely on it not changing - they just wouldn't be able to change it themselves.</p>
 

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