title: Prevent list element access from outside class c#
body: <p>As what might be a continuation of this <a href="https://stackoverflow.com/questions/2158160/prevent-other-classes-from-altering-a-list-in-a-class">question.</a></p>
  
  <p>I stepped into the need of having a list of class <code>List&lt;Foo&gt;</code> where I would like to restrict the access to the elements of the list, but not the access to the list as a whole, so that I can get/set the whole list, but not get/set any of its elements.</p>
  
  <p>The challenge is that the type of the elements of the list needs to be a public class with all its members (that are properties) public due to serialization of the list elements. </p>
  
  <p>Is there any way to implement this?</p>
  
  <p>Thanks in advance</p>
  
  <p>Edit:</p>
  
  <p>I attempted this:</p>
  
  <pre><code>public class SomeClass()
  {
      private List&lt;string&gt; someList;
      public IList&lt;string&gt; SomeList { 
          get { return someList.AsReadOnly(); }
      }
  }
  </code></pre>
  
  <p>And checked if there could be any method that provides my need that would be kind of <code>get { return someList.AsWholeListGettable&amp;SettableOnly(); }</code> or <code>get { return someList.AsNoAccessibleElementsList(); }</code></p>
  
  <p>I also tried the [] operator overload to try to make the index operator kind of private. (The same behaviour for an array would also be accepatable).</p>
  
  <pre><code>class SampleCollection&lt;T&gt;
  {
      // Declare an array to store the data elements.
      private T[] arr = new T[100];
  
      // Define the indexer to allow client code to use [] notation.
      private T this[int i]
      {
          private get { return arr[i]; }
          private set { arr[i] = value; }
      }
  }
  </code></pre>
  
  <p>as in <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/" rel="nofollow noreferrer">here</a>.</p>
  
  <p>So that from outside the class members wont be accesible. But I get this error:</p>
  
  <p><a href="https://i.stack.imgur.com/VVyP4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VVyP4.png" alt="enter image description here"></a></p>