Constant
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.