In this article, I am going to explain about Const, ReadOnly, & static ReadOnly keywords in C#.
Const keyword
It is used to declare a constant field and is also known as Compile-Time Constant. A constant field cannot be modified. So, if you want to assign a value to a variable that may be changed at any time in the future, please don't define it as constant. Constant variables, once declared, can never be changed further, i.e., neither in constructors nor in any method. Its value should only be assigned during its declaration time. It can only be used along with
built-in C# types.
As from the above image, it can be seen that constant value once assigned cannot be changed in any of the constructors.
From the above image, it can be seen that constant is not accessible by object reference. It is directly accessible by using a class name. That means, const is by default static and it should not be used along with the static keyword. Below is the example of using const keyword.
Programming Example 1 - using const keyword
- using System;
- namespace ConstStaticReadOnly {
- public class Constant {
- public
- const int iconstant = 2;
- public Constant() {
-
- }
- static Constant() {
-
- }
- }
- class Program {
- static void Main(string[] args) {
- Constant conObj = new Constant();
- Console.WriteLine(String.Format("Constant Value : { 0}", Constant.iconstant));
- }
- }
- }