Dictionary Meaning:
The meaning of “Constant” is “Something that does not or cannot change or vary.”
What is Constant?
Constants are unchangeable value that do not change for the life of the program. Constants are declared with the const modifier.
Let’s have a look at Const:
Constants are immutable values which are known at compile time and do not change for the life of the program. Value must be initialized,initialization must be at compile time.
This type of constant is called Compile time Constant.
For example:
- namespace ConstReadonly
- {
- class Program
- {
- public const int month = 12;
- static void Main(string[] args)
- {
- Console.WriteLine(month);
- Console.ReadKey();
- }
- }
- }
Notes: - To assign value to const is must, otherwise it’ll get compilation error (A const field requires a value to be provided).
- By default it is static, if we set it static it’ll get compilation error (Cannot be marked static).
- Value is hard coded.
- Can define const only on primitive types like int, double, etc.
Let’s have a look at Read-only:
Read-only variables can only being assigned on its declaration and another way is to assign value inside an instance/static constructor.
This type of constant is called Run time Constant.
For example:
- namespace ConstReadonly
- {
- class Program
- {
- public static readonly int week = 7;
- public const int month = 12;
- static void Main(string[] args)
- {
- Console.WriteLine(week);
- Console.ReadKey();
- }
- }
- }
- namespace ConstReadonly
- {
- class ReadOnly
- {
- public readonly int week = 7;
- public ReadOnly()
- {
- week = 10;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- ReadOnly objRn = new ReadOnly();
- Console.WriteLine(objRn.week);
- Console.ReadLine();
- }
- }
- }
Notes:
- To assign value is not mandatory, but once it is assigned that do not change for the life of the program.
- They can be static or instance.
- Must have set instance value.
- Value can be assigned at run-time. If we set the value directly it'll get a compilation error, A static read-only field cannot be assigned to (except in a static constructor or a variable initializer).