C-Sharp: Interesting Facts of Constants

What is constant in c#?

Constant is a symbol which value will never change in program life cycle. Values of constants is determined at compile time. You can also say constant a static member not an instance member which value will never change.

How compiler handles constants in program?

Compiler saves constant value in assembly metadata. When you refer a constant field in your program, it picks constant value from assembly metadata and embed value in generated IL code.

It does not required memory allocation at run time because it is directly embedded. Hence you can not get address of a constant and you can not pass it by reference.

Types and Constants

In C# you can define constants for all primitive types(Boolean, Char, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, and String).

How ever in C# you can define constants for non primitive reference type with assigning value null as given below i am defining constant of Windows Form class.

const Form FORM_C = null;

Note: A const field of a reference type other than string can only be initialized with null.

Precautions while using constants

Use constants only when you are sure that it value will be never change because as i have discussed earlier compiler saves constant values in assembly metadata and you are referencing this assembly in another assembly and using this constant then compiler will embed value of this constant in caller IL code.

Suppose you have created one assembly having constant const I_MAX = 1000 and referencing it in another assembly and later you have changed value of I_MAX in first assembly and compile only first assembly then it will not change value of I_MAX in second referencing assembly.

Suppose that you have an assembly with some constants and you are referencing these constants only in some other assembly, after compilation you can delete first assembly because it will be not loaded  at run time :).

blog comments powered by Disqus