<p>I have an object in a multi-threaded environment that maintains a collection of information, e.g.:</p>

<pre><code>public IList&lt;string&gt; Data 
{
    get 
    {
        return data;
    }
}
</code></pre>

<p>I currently have <code>return data;</code> wrapped by a <code>ReaderWriterLockSlim</code> to protect the collection from sharing violations.  However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there.  Is this at all possible?  </p>

[{'answer_id': 55507, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 6, 'selected': True, 'text': '<p>If your underlying data is stored as list you can use <a href="http://msdn.microsoft.com/en-us/library/e78dcd75.aspx" rel="noreferrer">List(T).AsReadOnly</a> method.<br>\nIf your data can be enumerated, you can use <a href="http://msdn.microsoft.com/en-us/library/bb342261.aspx" rel="noreferrer">Enumerable.ToList</a> method to cast your collection to List and call AsReadOnly on it.</p>\n'}, {'answer_id': 55551, 'author': 'Kris Erickson', 'author_id': 3798, 'author_profile': 'https://Stackoverflow.com/users/3798', 'pm_score': 2, 'selected': False, 'text': '<p>One should note that <a href="https://stackoverflow.com/questions/55502/return-collection-as-read-only#55507">aku</a>\'s answer will only protect the list as being read only.  Elements in the list are still very writable.  I don\'t know if there is any way of protecting non-atomic elements without cloning them before placing them in the read only list.  </p>\n'}, {'answer_id': 55661, 'author': 'nedruod', 'author_id': 5504, 'author_profile': 'https://Stackoverflow.com/users/5504', 'pm_score': 4, 'selected': False, 'text': "<p>If your only intent is to get calling code to not make a mistake, and modify the collection when it should only be reading all that is necessary is to return an interface which doesn't support Add, Remove, etc..  Why not return <code>IEnumerable&lt;string&gt;</code>?  Calling code would have to cast, which they are unlikely to do without knowing the internals of the property they are accessing.</p>\n\n<p>If however your intent is to prevent the calling code from observing updates from other threads you'll have to fall back to solutions already mentioned, to perform a deep or shallow copy depending on your need.</p>\n"}, {'answer_id': 59545, 'author': 'Daniel Fortunov', 'author_id': 5975, 'author_profile': 'https://Stackoverflow.com/users/5975', 'pm_score': 4, 'selected': False, 'text': "<p>I think you're confusing concepts here.</p>\n\n<p>The <code>ReadOnlyCollection</code> provides a read-only wrapper for an existing collection, allowing you (Class A) to pass out a reference to the collection safe in the knowledge that the caller (Class B) cannot modify the collection (i.e. cannot <strong>add</strong> or <strong>remove</strong> any elements from the collection.)</p>\n\n<p>There are absolutely no thread-safety guarantees.</p>\n\n<ul>\n<li>If you (Class A) continue to modify the underlying collection after you hand it out as a <code>ReadOnlyCollection</code> then class B will see these changes, have any iterators invalidated, etc. and generally be open to any of the usual concurrency issues with collections.</li>\n<li>Additionally, if the elements within the collection are mutable, both you (Class A) <strong>and</strong> the caller (Class B) will be able to change any mutable state of the objects within the collection.</li>\n</ul>\n\n<p>Your implementation depends on your needs:\n - If you don't care about the caller (Class B) from seeing any further changes to the collection then you can just clone the collection, hand it out, and stop caring.\n - If you definitely need the caller (Class B) to see changes that are made to the collection, and you want this to be thread-safe, then you have more of a problem on your hands. One possibility is to implement your own thread-safe variant of the ReadOnlyCollection to allow locked access, though this will be non-trivial and non-performant if you want to support IEnumerable, and it <em>still</em> won't protect you against mutable elements in the collection.</p>\n"}, {'answer_id': 110479, 'author': 'Dror Helper', 'author_id': 11361, 'author_profile': 'https://Stackoverflow.com/users/11361', 'pm_score': 2, 'selected': False, 'text': "<p>You can use a copy of the collection instead.</p>\n\n<pre><code>public IList&lt;string&gt; Data {\nget {\n    return new List&lt;T&gt;(data);\n}}\n</code></pre>\n\n<p>That way it doesn't matter if it gets updated.</p>\n"}, {'answer_id': 110515, 'author': 'Charles Graham', 'author_id': 7705, 'author_profile': 'https://Stackoverflow.com/users/7705', 'pm_score': 2, 'selected': False, 'text': '<p>You want to use the <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="nofollow noreferrer">yield</a> keyword.  You loop through the IEnumerable list and return the results with yeild.  This allows the consumer to use the for each without modifying the collection.</p>\n\n<p>It would look something like this:</p>\n\n<pre><code>List&lt;string&gt; _Data;\npublic IEnumerable&lt;string&gt; Data\n{\n  get\n  {\n    foreach(string item in _Data)\n    {\n      return yield item;\n    }\n  }\n}\n</code></pre>\n'}, {'answer_id': 1931338, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 4, 'selected': False, 'text': '<p>I voted for your accepted answer and agree with it--however might I give you something to consider?</p>\n\n<p>Don\'t return a collection directly. Make an accurately named business logic class that reflects the purpose of the collection.</p>\n\n<p>The main advantage of this comes in the fact that you can\'t add code to collections so whenever you have a native "collection" in your object model, you ALWAYS have non-OO support code spread throughout your project to access it.</p>\n\n<p>For instance, if your collection was invoices, you\'d probably have 3 or 4 places in your code where you iterated over unpaid invoices. You could have a getUnpaidInvoices method.  However, the real power comes in when you start to think of methods like "payUnpaidInvoices(payer, account);".</p>\n\n<p>When you pass around collections instead of writing an object model, entire classes of refactorings will never occur to you.</p>\n\n<p>Note also that this makes your problem particularly nice. If you don\'t want people changing the collections, your container need contain no mutators. If you decide later that in just one case you actually HAVE to modify it,  you can create a safe mechanism to do so.</p>\n\n<p>How do you solve that problem when you are passing around a native collection?</p>\n\n<p>Also, native collections can\'t be enhanced with extra data. You\'ll recognize this next time you find that you pass in (Collection, Extra) to more than one or two methods. It indicates that "Extra" belongs with the object containing your collection.</p>\n'}]
['https://Stackoverflow.com/questions/55502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5296/']