I have a code which is shown below. I was asked in an interview
object global;
void f()
{
object local=new object();
global=local;
}
He asked, “Is global null outside the function?”. Since the local variable loses its scope outside the function and its reference is given to global it should also be null but it isn’t why?
You have to differentiate between variables and values.
The local variable only exists inside the function, but that doesn’t mean that the value that the variable contains doesn’t exist outside the function.
When you assign the value of
localtoglobal, you are copying the reference to the object so that there are two reference to the same object. The local variable goes away when you leave the function, but the value that you copied to the global variable still exists, and the object survives as there is still a reference to it.