2

What gets pushed onto the stack when an object is called by reference? Consider this code:

using System;
class em
{
   public int i=0;
}
class program
{
    public void method(int a, ref int b, em c, ref em d)
    {
         //implementation
    }
    static public void Main()
    {
         int i;
         int j;
         em e1 = new em();
         em e2 = new em();
         i=9;
         j=10;
         Program p=new Program();
         p.method(i,ref j,e1,ref e2);
    }
}

When e1 is passed , the reference of the object is passed as an argument but in this code when e2 is passed by reference, what is pushed onto the stack i.e., what is passed as the argument to the method ? And what is passed when the same object is returned using ref .

123
  • 41
  • 8

2 Answers2

1

Classes are reference types and when you passes instance as parameter, the pointer (reference) of object copied. But when you use ref keyword, the pointer itself is passed and any changes is directly done on original reference. See the code bellow:

class program
{
    static public void method(int a, ref int b, em c, ref em d)
    {
        c = null; // c is copy of e1
        d = null; // d is e2
    }
    static public void Main()
    {
        int i;
        int j;
        em e1 = new em(); // e1 is pointer to 'new em()' location at memory
        em e2 = new em(); // e2 is pointer to 'new em()' location at memory
        i = 9;
        j = 10;
        method(i, ref j, e1, ref e2);
        // e1 is intact
        // e2 is null
    }
}
Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27
  • if address of the object on heap is #001 , while passing by value this address gets passed. if ref keyword is used, address of location on stack where #001 is stored is passed .Am I right ? – 123 Jun 01 '18 at 11:36
  • in case of passing by value: additional copy of existing pointer [with value of #001] copied [with value of #001] and both are pointing to object location at address #001. in case of passing by ref: existing pointer [with value of #001] is the only pointer that points to object location at address #001. – Hossein Golshani Jun 01 '18 at 12:10
0

The data exists on the heap since e2 is not a value type, so just a reference to the heap address is stored on the stack. So you are not passing e2, just a reference to e2.

This is a good link showing the differences between value and reference types and where they are stored.

Lucax
  • 407
  • 2
  • 10