user3079266
user3079266

Reputation:

C# - when at runtime is a const field initialized

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?

Upvotes: 0

Views: 777

Answers (2)

Guffa
Guffa

Reputation: 700352

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.

Upvotes: 5

Peter Duniho
Peter Duniho

Reputation: 70671

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

Upvotes: 4

Related Questions