Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you assign reference of local variable inside method to public static variable

Meanwhile reading on the internet I learned that static variables always have the same memory address. So when compiling the program, the compiler is going to decide what memory address to assign to the static variables. Reading that made me think about what happens when you do:

class Foo {}

class Program
{
    public static Foo someStaticVar;

    static void Main(string[] args)
    {
        Foo localVariable = new Foo();

        int x = 4;

        someStaticVar = localVariable; // is someStaticVariable still will have the same address?
    } 
    // variable x will be pushed of the stack
    // localVariable will be pushed of the stack
    // what happens then with someStatic var? 
}

I also learned that when declaring variables inside a method they will be pushed to the stack when created and popped out the stack when the method returns. If all that is true then someStaticVar should disappear but it doesn't.

I am sure I must understood something incorrectly. Or maybe on the line someStaticVar = localVariable; is performing a deep copy of that object but I doubt it because there are a lot of questions on the interenet on how to do a deep copy of an object and they are much different than this approach.

like image 843
Tono Nam Avatar asked Feb 19 '23 03:02

Tono Nam


1 Answers

In the example you provided localVariable is only a local variable to the Main method. It falls out of scope once the Main method ends executing. But since you have assigned it to the static field, the Foo instance that was created will continue to live outside of the Main method. And since it is static field it will live even outside of the Program class.

So here's what happens step by step:

static void Main(string[] args)
{
    // an instance of Foo is created and pushed on the heap
    // localVariable is now pointing to the address of this instance
    // localVariable itself is stored on the stack
    Foo localVariable = new Foo();

    // someStaticVar is now pointing to the same location on the heap as
    // the localVariable - the Foo instance created earlier
    someStaticVar = localVariable; 
} 
// at this stage the Main method finishes executing and all local
// variables are falling out of scope. But since you have a static variable
// pointing to the Foo instance that was created inside the Main method this
// instance is not illegible for garbage collection because there are still 
// references to it (someStaticVar).

If someStaticVar was an instance field and not static then the same process will happen except that the instance will fall out of scope once there are no longer any references to the containing class (Program).

like image 156
Darin Dimitrov Avatar answered Apr 26 '23 06:04

Darin Dimitrov