Initialization Order of Static Fields in Static Class

前端 未结 3 1030
庸人自扰
庸人自扰 2020-11-27 05:29

given the following code:

public static class Helpers
{
   private static Char[] myChars = new Char[] {\'a\', \'b\'};

   private static Int32 myCharsSize =          


        
3条回答
  •  旧时难觅i
    2020-11-27 05:46

    Yes, they will, please see 10.4.5.1 Static field initialization:

    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.

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

提交回复
热议问题