Do static members of a class get initialized even before static constructor gets called?

649 views Asked by At

I was reading MSDN Documentation and there seems to be a contradiction.

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.

also in the next paragraph or so,

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

If static constructor's purpose is to initialize static members of the class then how come it says that static members get initialized even before static constructor gets called?

Is it like if I write:

public  static int age = 10;

static SimpleClass()
{
 age = 20;
}

Does that mean that age first gets initialized to 10 and then the value is overwritten to 20?

1

There are 1 answers

1
AudioBubble On

The second quote is a recommendation: Microsoft recommends using the static constructor instead of initializing fields when declaring, to avoid ordering issues, especially when using partial classes, which can cause null exceptions.

Indeed, by using partial classes, the order of assignment of the fields is not guaranteed. Using the static constructor, it does.

You can also use properties to make sure that you don't get a null exception if the getters don't access instances of uninitialized reference types.

So, because of the first quote, the answer to your question is: yes, it means that age first gets initialized to 10 and then the value is overwritten to 20, unless you are using partial classes, then the result may be hazardous and it can be a fight against the debugger...

You can check and inversigate this by playing around with breakpoints.