Thursday, January 25, 2018

Constant and Fields

Constant 


Constant is a symbol,  the value of which is never changed. As it's value is assigned at compile time so, the compiler saves the constant value in assembly metadata.

Constant can only be of primitive type  i.e; Boolean, Char, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal and String.
One exception to above is that you can have constant of non-primitive type but with value as null.
e.g; public const MyClassType ClassConst = null;

Constants are implicitly static members.

Whenever a constant is called, compiler search for it in the assembly metadata where constant is defined and embed the constant value in the intermediate Language (IL) of caller code.

For Constant no memory is required at run time as it's value is already embedded in the code. Which means that constants have no address and can't be passed as reference.
Also,  because of the embedding versioning of constants are not possible.

Fields


It's a data member that holds the instance of a value type or reference of a reference type.
Fields are stored in memory, so,  there value can be read,  write or updated at run time.

Versioning is possible with fields and variables need not to be of primitive data types as constants.

The modifiers that can be used with fields are:
  • Static
  • Instance type (default) 
  • Readonly
  • Volatile 

Readonly Fields
  • The value can only be altered in the constructor. 
  • Reflection can be used to change fields value 
  • If the field is of reference type and readonly, the reference is immutable and not the object field refers to. 


No comments:

Post a Comment