Will local variable assignment be performed even if the variable is not used?

I have a static container class that contains a handle to some class A

:

public static class Container
{
    private static A _a;        
    public static void Register(A a) { _a = a; }
    public static void Run() { _a.DoIt(); }
}

      

Registering a container instance is A

done in the constructor A

:

public class A
{
    public A() { Container.Register(this); }        
    public void DoIt() { Console.WriteLine("Running!"); }
}

      

Now let's say that I register my instance A

by calling a method that only contains A

:

public void Init() { var a = new A(); }

      

In theory, is it possible to optimize compilation to ignore this assignment, or can I be 100% sure that A

it is always created when I call a method Init

?

Example When I run the following code:

Init();
...
Container.Run();

      

will the Container._a

output from the method DoIt

written to the console always be defined ?

+3


source to share


1 answer


The compiler doesn't know at all if A's constructor has observable side effects, so it will always call it. It might not store the "a" variable.

So, the constructor will be called, but the result cannot be assigned to a variable; instead, object A can immediately be registered for garbage collection immediately if nothing else references it. (In your case, something else points to this, namely the Container class, so it will NOT be garbage collected!)

In your case, the constructor clearly has side effects anyway (so it would be a big mistake for the compiler to optimize the constructor call).



In short:

  • The constructor will always be called.
  • The assignment of the result to a local variable cannot be done because the compiler knows it has no observable side effects.
  • Something else in your code keeps a reference to the constructed object, so it won't be GCed.
+7


source







All Articles