When the class variable "Constant" is initialized

I have a constant int variable defined as a class variable:

My class is defined like this:

public class ABC : XYZ
{
    private const int constantNumber = 600;

    public ABC(): base(constantNumber)
    {}

}

      

Will it be available by the time the base constructor is called (i.e., before its own constructor is called)?

When is it determined exactly?

+3


source to share


2 answers


It is available even without class initialization! Basically, wherever a constant is used, the compiler will insert the value.

For example:

public class Constants
{
    public const int Foo = 10;

    static Constants()
    {
        Console.WriteLine("Constants is being initialized");
    }
}

class Program
{
    static void Main()
    {
        // This won't provoke "Constants is being initialized"
        Console.WriteLine(Constants.Foo);
        // The IL will be exactly equivalent to:
        // Console.WriteLine(10);
    }
}

      



Even with a variable, static readonly

you can still use it wherever you use it, because it is associated with a type, not an instance of the type. Don't forget that const

implicitly static

(and you cannot specify it explicitly).

As a side note (mentioned in the comments) this "nesting" means that you should use const

for things that are indeed constants. If the Constants

and Program

above were in different assemblies, but Constant.Foo

were changed to have a value of 20, then Program

it will need to be recompiled before the change is used. This is not the case for a field static readonly

whose value is retrieved at run time, not at compile time.

(This also affects the default values ​​for optional parameters.)

+9


source


At compile time, it is compiled directly into the resulting DLL, so it is available long before the program even starts running.



As MarkO points out, when a constant is used in assembly B from A, the value from A will compile directly to B. So if you update and rewrite A with the change value, B will not be reflected on it.

+4


source







All Articles