Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization Order of Static Fields in Static Class

given the following code:

public static class Helpers {    private static Char[] myChars = new Char[] {'a', 'b'};     private static Int32 myCharsSize = myChars.Length; } 

Is it guaranteed that myChars will be initialized before I use its length to assign to myCharsSize?

like image 427
Alex Avatar asked Sep 29 '09 20:09

Alex


People also ask

How do you initialize a static field?

The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.

Which constructor is called first in C# static or default?

That's why you can see in the output that Static Constructor is called first. Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.

Can static classes be initialized?

Yes and yes. Note that it is possible to construct code where you can observe the default initialized value of a static field.

How are static variables initialized in Java?

In Java, static variables are also called class variables. That is, they belong to a class and not a particular instance. As a result, class initialization will initialize static variables. In contrast, a class's instance will initialize the instance variables (non-static variables).


1 Answers

Yes, they will, please see clause 15.5.6.2 of the C# specification:

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 (§15.5.6.1). Within a partial class, the meaning of "textual order" is specified by §15.5.6.1. If a static constructor (§15.12) 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.

That being said I think it would be better to do the initialization inside a static type initializer (static constructor).

like image 79
Andrew Hare Avatar answered Sep 22 '22 12:09

Andrew Hare