title: Given a managed reference to a struct, how to obtain a managed reference to a field at offset?
body: <p>I am trying to implement fixed size arrays in C#, that are parametrized by hacky type-level numerics. See <a href="https://github.com/losttech/TypeNum/" rel="nofollow noreferrer">GitHub</a></p>
  
  <p>I want to implement a method, that would work like this:</p>
  
  <pre><code>static ref T Ref(this ref TContainer container, int index)
    where T: unmanaged
    where TContainer: unmanaged
    =&gt; ref container[index];
  </code></pre>
  
  <p>Now the problem is: I know, that <code>TContainer</code> internally consists of N fields of type <code>T</code>. But it does not actually implement the indexing operation (or any interface whatsoever).</p>
  
  <p>What I can do is:</p>
  
  <pre><code>CheckIndex(index);
  fixed (TContainer* self = &amp;container) {
      T* data = (T*)self;
      return ref data[index];
  }
  </code></pre>
  
  <p>This compiles with <code>unsafe</code>, but I have two questions:</p>
  
  <ol>
  <li>Will the lifetime of the managed reference retrieved like this be tracked properly?</li>
  <li>Does use of <code>fixed</code> in this context have any performance cost? (e.g. GC pinning, aliasing issues, etc)</li>
  </ol>
  
  <p>Additionally, the example with <code>fixed</code> and <code>return ref</code> from above also compiles even when I replace the parameter type <code>ref TContainer</code> with just <code>TContainer</code>, or, which should be the same, just declare it as an instance member instead of an extension method. It even works in a sample test case, but I can't see why it does, because under normal circumstances one can't return <code>ref this.field</code> from a struct instance method.</p>