In C# if i declare a constant variable is any memory allocated to it as it acts as a compile time replacement? How long is the variable's life?
2 Answers
Literal const
s are compile time replacements. Section 14.16 in the spec I have handy:
A constant expression is an expression that shall be fully evaluated at compile-time.
-
ok...so does it get a memory allocated to it? and is it alive as long the application is running?– babanMay 12, 2013 at 16:06
-
It depends.
public const double pi = 3.14
will simply replace anywherepi
is referenced with the constant3.14
. The constant itself will be part of the bytecode and thus takes up space (in the compiled CIL), but no more than literally putting "3.14" everywhere instead of "pi". And since it lives in bytecode, it does not ever live, per se.– TelastynMay 12, 2013 at 16:15
No memory is allocated since the value is put directly into code. The compiler places the constant in the assembly metadata, so the lifetime of the constant is the lifetime of the assembly it's in.
-
even i thought so and searched for the same over the net...but could not be sure...– babanMay 12, 2013 at 16:07
const
can only be applied to strings & numerical values, and not objects. Those have to be qualified withstatic readonly
.const SomeReferenceType constField = null;
.final
(with its multitude of meanings).