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 consts 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?baban– baban2013-05-12 16:06:30 +00:00Commented May 12, 2013 at 16:06
- It depends.
public const double pi = 3.14will simply replace anywherepiis 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.Telastyn– Telastyn2013-05-12 16:15:14 +00:00Commented May 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...baban– baban2013-05-12 16:07:44 +00:00Commented May 12, 2013 at 16:07
constcan 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).