Passing array elements by ref
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/2500851/c-sharp-parameters-by-reference-and-net-garbage-collection">C# parameters by reference and .net garbage collection</a>  </p>
</blockquote>



<p>I was thinking of using ref arguments to limit the bounds checking of an array. For example the code of swapping two elements is :</p>

<pre><code>class Test {
  int[] array;

  private void qSort() {
    ...blah...
    int temp = array[a];
    array[a] = array[b];
    array[b] = temp;
  }
}
</code></pre>

<p>which has 4 access to the array
the alternative will be :</p>

<pre><code>class Test {
  int[] array;

  private void qSort() {
  ...blah...
    Swap( ref array[a], ref array[b] );
  }

  static void Swap(ref int a,ref int b) {
    int temp = a;
    a=b;
    GC.Collect();  // suppose this happens
    b=temp;
  }
}
</code></pre>

<p>which theoretically has only 2 access to the array</p>

<p>What confusing me is that I don't know what exactly happens when I pass an array element by ref. If Garbage Collector kicks in, while executing code in the Swap function, will be able to move the array ? or the array is pinned for the duration of the call ?</p>

<p>Mind that the above code is a simple test case. I want to use it in much more complex scenarios</p>

<p>Edit: As  BrokenGlass pointed out, this is answered by Eric Lippert here <a href="http://stackoverflow.com/questions/2500851/c-sharp-parameters-by-reference-and-net-garbage-collection">C# parameters by reference and .net garbage collection</a></p>

<p>The array will not be pinned and GCollector can move it and will update accordinly any ref to an element of it, that resides on the stack</p>
