C# parameters by reference and .net garbage collection
        Posted  
        
            by Yarko
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Yarko
        
        
        
        Published on 2010-03-23T14:53:14Z
        Indexed on 
            2010/03/23
            16:23 UTC
        
        
        Read the original article
        Hit count: 361
        
pass-by-reference
|c#
I have been trying to figure out the intricacies of the .NET garbage collection system and I have a question related to C# reference parameters. If I understand correctly, variables defined in a method are stored on the stack and are not affected by garbage collection. So, in this example:
public class Test
{
 public Test()
 {
 }
 public int DoIt()
 {
  int t = 7;
  Increment(ref t);
  return t;
 }
 private int Increment(ref int p)
 {
  p++;
 }
}
the return value of DoIt() will be 8. Since the location of t is on the stack, then that memory cannot be garbage collected or compacted and the reference variable in Increment() will always point to the proper contents of t.
However, suppose we have:
public class Test
{
 private int t = 7;
 public Test()
 {
 }
 public int DoIt()
 {
  Increment(ref t);
  return t;
 }
 private int Increment(ref int p)
 {
  p++;
 }
}
Now, t is stored on the heap as it is a value of a specific instance of my class. Isn't this possibly a problem if I pass this value as a reference parameter? If I pass t as a reference parameter, p will point to the current location of t. However, if the garbage collector moves this object during a compact, won't that mess up the reference to t in Increment()? Or does the garbage collector update even references created by passing reference parameters? Do I have to worry about this at all? The only mention of worrying about memory being compacted on MSDN (that I can find) is in relation to passing managed references to unmanaged code. Hopefully that's because I don't have to worry about any managed references in managed code. :)
© Stack Overflow or respective owner