Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
Is it a primitive? Or object? –  MichaelT May 12 '13 at 14:05
    
@MichaelT If I recall, const can only be applied to strings & numerical values, and not objects. Those have to be qualified with static readonly. –  Richard J. Ross III May 12 '13 at 14:16
    
@RichardJ.RossIII With one exception: you can do const SomeReferenceType constField = null;. –  svick May 12 '13 at 14:57
    
@RichardJ.RossIII ahh - please pardon my java-ness for that where we've only got final (with its multitude of meanings). –  MichaelT May 13 '13 at 3:44

2 Answers 2

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.

share|improve this answer
    
even i thought so and searched for the same over the net...but could not be sure... –  baban May 12 '13 at 16:07

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.

share|improve this answer
    
ok...so does it get a memory allocated to it? and is it alive as long the application is running? –  baban May 12 '13 at 16:06
    
It depends. public const double pi = 3.14 will simply replace anywhere pi is referenced with the constant 3.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 May 12 '13 at 16:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.