none
What is stored in stack when object is passed by reference RRS feed

  • Question

  • what gets pushed onto the stack when an object is called by reference. Consider below 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 passed ,the reference of the object is passed as the 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 ?

    Friday, June 1, 2018 8:05 AM

All replies

  • All parameters are passed on the stack in pretty much every stack based language (excluding the fact that the compiler can save a little space by using registers). So every parameter (irrelevant of type) is allocated space at function prologue. So in your example 'method' would get space for each of the 4 parameters. Ref parameters are effectively pointers so it'd be 4 bytes in x86 mode and 8 in x64 mode. For ref parameters or ref types then the underlying reference (pointer) is put onto the stack so that both sides can easily access it. For value types then the value is copied just as it would in any other language.

    Note that parameters are really just glorified local variables and they all get allocated at the same time so everything that applies to locals works with parameters.

    When e2 is passed by reference, since it is a ref parameter, then the compiler just stores a reference (pointer) to it. But note that this is an implementation detail in most languages. A language may, if they so choose, decide to do a copy by value approach during the prologue and then copy the (modified) value back to the original argument during function epilogue. But this is inefficient compared to simply passing the reference to it directly hence why most languages (that I'm aware of) do it that way.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, June 1, 2018 1:51 PM
    Moderator