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)
{}
}
Would it be available by the time it calls the base constructor (i.e. before calling it's own constructor)?
When exactly does it get defined?
It's available even without the class being initialized! Basically, everywhere the constant is used, the compiler will inline 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 static readonly
variable, you'd still be able to use it where you're currently using it - because it's related to the type rather than an instance of the type. Don't forget that const
is implicitly static
(and you can't state that explicitly).
As a side note (mentioned in comments) this "embedding" means that you should only use const
for things which really are constants. If Constants
and Program
above were in different assemblies, and Constant.Foo
were changed to have a value of 20, then Program
would need to be recompiled before the change would be usable. That isn't the case with a static readonly
field, whose value is retrieved at execution time instead of being embedded at compile time.
(This also affects default values for optional parameters.)
See more on this question at Stackoverflow