Learner
Learner

Reputation: 4751

Why the static variable is not set to null when the local variable storing that reference is set to null?

I have following code :

public class Employee
{
    public string Name { get; set; }
}

public class InstanceManager
{
    public static Employee employee;

    public static Employee GetEmployee()
    {
        if(employee == null)
        {
            employee = new Employee {Name = "Tom"};
        }

        return employee;
    }
}

public class TestClass
{

    public void Test()
    {
        Employee emp = InstanceManager.GetEmployee();
        var name = emp.Name;
        emp = null;
        var name2 = InstanceManager.GetEmployee().Name;
    }
}

In the Test() method, local variable emp is referencing InstanceManager.Employee object. Then, I set emp to null.

(I was expecting that new Employee object will be created and returned by the GetEmployee() method when I call this method after emp = null;.)

Upvotes: 1

Views: 3598

Answers (4)

Ravi Patel
Ravi Patel

Reputation: 463

"emp" is a new instace of Employee inside Test class. And it do not refer to static variable employee. Because,

    Employee emp = InstanceManager.GetEmployee();

will get the value and assign to emp.

Conclusion: instance emp (of Test class) and employee(of InstanceManager class) are both different.

Upvotes: -1

BartoszKP
BartoszKP

Reputation: 35891

After this line:

Employee emp = InstanceManager.GetEmployee();

your situation looks like this:

enter image description here

When you do:

emp = null;

afterwards, you're not altering the static variable employee. You are just setting emp to reference another (in this case null) "location". More precisely - you're setting it not to point to anything. The static employee keeps pointing to where it was. The effect of this line can be visualized like this:

enter image description here

Upvotes: 8

ken2k
ken2k

Reputation: 48985

What you are doing is basically:

Employee emp = InstanceManager.GetEmployee();

emp now is a reference to the employee instance

emp = null;

emp is no more a reference to the employee instance

var name2 = InstanceManager.GetEmployee().Name;

name2 now is a reference to the employee.Name instance

You're never setting null to InstanceManager.employee. There isn't even a public setter for it btw.

Upvotes: 6

Paul Coghill
Paul Coghill

Reputation: 677

Doesn't that mean that I am setting InstanceManager.Employee to null?

No. You are only setting "emp", iself as a local variable to null.

If I debug this code, I find that employee static variable of the InstanceManager is NOT null! Why?

You would need to implement a public setter for the employee property. You could just make the property public.

You could also add something like this to the Instance Manager:

           public static void ClearEmployee()
            {
                employee = null;
            }

As this references the static field explicitly.

Upvotes: -1

Related Questions