What is the best way to expose a List<T> as readonly?
<p>I've been around this design problem many times, and never found a killer solution.</p>

<p>I want to expose a collection that is editable in the owner <code>class</code> scope, but only readable for other public scopes.</p>

<p><strong>Trial 1:</strong></p>

<pre><code>public class MyClass
{
    private List&lt;object&gt; _myList = new List&lt;object&gt;();

    public IEnumerable&lt;object&gt; MyList { get { return _myList; } }
}
</code></pre>

<p>The problem with this is a external code can just cast it back to <code>List</code> and edit, like this:</p>

<pre><code>var x = ((List&lt;object&gt;)MyList);
</code></pre>

<p><strong>Trial 2:</strong></p>

<pre><code>public class MyClass
{
    private List&lt;object&gt; _myList = new List&lt;object&gt;();

    public IEnumerable&lt;object&gt; MyList { get { return _myList.ToList(); } }
}
</code></pre>

<p>This way we prevent external modification, but create a unnecessary overhead of copying the <code>List</code> many times.</p>

<p><strong>Trial 3:</strong></p>

<pre><code>public class MyClass
{
    private List&lt;object&gt; _myList = new List&lt;object&gt;();
    private ReadOnlyCollection&lt;object&gt; _roList = 
        new ReadOnlyCollection&lt;object&gt;(_myList)

    public IEnumerable&lt;object&gt; MyList { get { return _roList; } }
}
</code></pre>

<p>This is the standard solution, wich I use currently, but <code>ReadOnlyCollection</code> is about 30% slower:</p>

<pre><code>Debug Trace:
Use normal foreach on the ReadOnlyCollection
Speed(ms): 2520,3203125
Result: 4999999950000000

use&lt;list&gt;.ForEach
Speed(ms): 1446,1796875
Result: 4999999950000000

Use normal foreach on the List
Speed(ms): 1891,2421875
Result: 4999999950000000
</code></pre>

<p>Is there a 'perfect' way of doing this? Thanks.</p>
