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?

  • Is it a primitive? Or object?
    – user40980
    May 12, 2013 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. May 12, 2013 at 14:16
  • @RichardJ.RossIII With one exception: you can do const SomeReferenceType constField = null;.
    – svick
    May 12, 2013 at 14:57
  • @RichardJ.RossIII ahh - please pardon my java-ness for that where we've only got final (with its multitude of meanings).
    – user40980
    May 13, 2013 at 3:44

2 Answers 2


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
    May 12, 2013 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, 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
    May 12, 2013 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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