title: Storing a C# reference to an array of structs and retrieving it - possible without copying?
body: <p>UPDATE: the next version of C# has a feature under consideration that would directly answer this issue. c.f. answers below.</p>
  
  <hr>
  
  <p>Requirements:</p>
  
  <ol>
  <li>App data is stored in arrays-of-structs. There is one AoS for each type of data in the app (e.g. one for MyStruct1, another for MyStruct2, etc)</li>
  <li>The structs are created at runtime; the more code we write in the app, the more there will be.</li>
  <li>I need one class to hold references to ALL the AoS's, and allow me to set and get individual structs within those AoS's</li>
  <li>The AoS's tend to be large (1,000's of structs per array); copying those AoS's around would be a total fail - they should never be copied! (they never need to!)</li>
  </ol>
  
  <p>I have code that compiles and runs, and it works ... but is C# silently copying the AoS's under the hood every time I access them? (see below for full source)</p>
  
  <pre><code>public Dictionary&lt;System.Type, System.Array&gt; structArraysByType;
  
  public void registerStruct&lt;T&gt;()
  {
      System.Type newType = typeof(T);
      if( ! structArraysByType.ContainsKey(newType ) )
      {
          structArraysByType.Add(newType, new T[1000] ); // allowing up to 1k
      }   
  }
  
  public T get&lt;T&gt;( int index )
  {
      return ((T[])structArraysByType[typeof(T)])[index];
  }
  
  public void set&lt;T&gt;( int index, T newValue )
  {
      ((T[])structArraysByType[typeof(T)])[index] = newValue;
  }
  </code></pre>
  
  <p>Notes:</p>
  
  <ul>
  <li>I need to ensure C# sees this as an array of value-types, instead of an array of objects ("don't you DARE go making an array of boxed objects around my structs!"). As I understand it: Generic T[] ensures that (as expected)</li>
  <li>I couldn't figure out how to express the type "this will be an array of structs, but I can't tell you which structs at compile time" other than System.Array. System.Array <em>works</em> -- but maybe there are alternatives?</li>
  <li>In order to index the resulting array, I have to typecast back to T[]. I am scared that this typecast <em>MIGHT</em> be boxing the Array-of-Structs; I know that if it were (T) instead of (T[]), it would definitely box; hopefully it doesn't do that with T[] ?</li>
  <li>Alternatively, I can use the System.Array methods, which definitely boxes the incoming and outgoing struct. This is a fairly major problem (although I could workaround it if were the only way to make C# work with Array-of-struct)</li>
  </ul>