Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why CLR optimizing away unused static field with initialization?

Let's have two code snippets:

A:

public class Foo
{
    private static Bar _unused = new Bar();
}

B:

public class Foo
{
    private static Bar _unused;

    static Foo()
    {
        _unused = new Bar();
    }
}

In case A the CLR will not even call the Bar ctor (unless it is debug build or the debugger is attached), however in case B it is called under all circumstances.

The thing is that in Bar constructor one can have calls that will make this instance reachable from elsewhere - most typically events subscriptions.

So:

  • Why are the cases A and B evaluated differently?
  • Why the CLR is not calling Bar ctor at all in case A - as it should not evaluate it as garbage until ctor is finished and instance is assigned to the appropriate field?
like image 363
Jan Avatar asked Oct 01 '15 10:10

Jan


1 Answers

If you don't create a constructor:

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

If you do have a static constructor:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

like image 165
CodeCaster Avatar answered Oct 27 '22 11:10

CodeCaster