Reputation: 15981
I have a static container class that holds 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(); }
}
Registration of the container A
instance is performed in the A
constructor:
public class A
{
public A() { Container.Register(this); }
public void DoIt() { Console.WriteLine("Running!"); }
}
Now, let's say that I register my A
instance by calling a method that only contains an A
instantiation:
public void Init() { var a = new A(); }
Theoretically, could compilation be optimized to ignore this assignment, or can I be 100% sure that A
is always instantiated when I call the Init
method?
Example When I run the following code:
Init();
...
Container.Run();
will Container._a
always be defined and the output from the DoIt
method written to the console?
Upvotes: 3
Views: 165
Reputation: 109577
The compiler doesn't in general know if the constructor of A has observable side-effects, so it will always call it. It may not keep the variable 'a' around though.
So, the constructor will be called, but the result may not be assigned to the variable; instead the A object may just be immediately registered for garbage collection if nothing else references it. (In your case, something else DOES reference it - namely, the Container class - so it WON'T be garbage-collected!)
In your case, the constructor manifestly DOES have side-effects in any case (so it would be a major error for the compiler to optimise away the constructor call).
In summary:
Upvotes: 7