1

For some reason, I've failed to find documentation on this. It looks like, in C#, the const fields of a class are initialized before static fields, as it can be seen from this code:

class Program {
    static int p = f;
    const int f = 10;

    static void Main(string[] args){
        System.Console.WriteLine("{0}", p);
        System.Console.ReadLine();
    }
}

(this outputs 10, while if I replace const with static, it outputs 0).

The question is: Is such behaviour always the case? Also, what is, generally, the order of initialization of different kinds of static class fields?

  • *const*s are compile time values. static variables are initialized at runtime in the order they declared... – L.B Oct 25 '14 at 18:37

2 Answers2

5

Constants are not initialised at all, they are constant values that are substituted at compile time. When the code runs, it's as if it was originally:

static int p = 10;

A side effect of this compile time substitution, is that constants that exist in one assembly and used in a different assembly requires both assemblies to be recompiled if you change the constant.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Thank you, I had some trouble comprehending it in the context of fields. –  Oct 26 '14 at 08:07
4

const declares a value that is determined at compile time. In the compiled code, it appears simply as a literal, rather than a reference to some named identifier. So, yes…const members are always "initialized" before any other member, inasmuch as they are "initialized" at all.

Here is a reasonably complete answer to your broader question: What is the static variable initialization order in C#?

Here are a couple of links to the documentation that should help as well:

10.4.5.1 Static field initialization

10.4.5.2 Instance field initialization

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136