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.
In the example you provided
localVariableis only a local variable to theMainmethod. 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:
If
someStaticVarwas 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).