Const and Read-Only in C#

Const and Read-Only in C# with Examples

In this article, I am going to discuss the need and use of the keywords Const and Read-only in C# with examples. Please read our previous article where we discussed the Static and Non-Static Members in C# with examples. The const and read-only are very two useful keywords in C# and also a little confusing to understand. So, as part of this article, we are going to discuss the following pointers in detail.

  1. Const Variable in C#.
  2. Example using Const variable.
  3. The read-Only variable in C#.
  4. Example using the read-only variable.
  5. Difference between Const, Readonly, Static and non-static variable in C#.
According to MSDN

Constants are the immutable values that are known at the time of program compilation and do not change their values for the lifetime of the program. The Read-only variables are also immutable values but these values are known at runtime and also do not change their values for the life of the program.

With the above definition in mind, let’s try to understand the const and readonly with some examples.

Const Variable in C#:
  1. The keyword const is used to create a “constant” variable. It means it will create a variable whose value is never going to be changed. In simple words, we can say that the variable whose value cannot be changed or modified once after its declaration is known as a constant variable.
  2. Constants are static by default.
  3. It is mandatory to initialize a constant variable at the time of its declaration.
  4. The behavior of a constant variable is the same as the behavior of a static variable i.e. maintains only one copy in the life cycle of class and initialize immediately once the execution of the class start (object not required)
  5. The only difference between a static and constant variable is that the static variable value can be modified but a constant variable value can never be modified.

Note: As we already discussed constants variable should be assigned a value at the time of variable declaration and hence these values are known at compile time. So, whenever we declare a constant variable, the C# compiler substitutes its value directly into the Intermediate Language (MSIL).

Example: Const Variable in C#

Let us understand the Const keyword in C# with an example. Please have a look at the following example. As you can see in the below code, within the ConstExample class, we declare a const variable i.e. public const int number = 5; and within the program class Main method we access the const variable by using the class name. This is because const are static by default and as static it does not require an object instead it can be accessed by using the class name. It is also possible to declare local variables as const i.e. we can declare const variable within a method also. In our example, within the Main method we declare a const variable i.e. const int no = 10;. But once we declare the const variable, then we cannot change its value and if we try to change the value of the const variable in C#, then we will get a compile-time error.

namespace ConstDemo
{
    class ConstExample
    {
        //we need to assign a value to the const variable
        //at the time of const variable declaration else it will
        //give compile time error
        public const int number = 5;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Const variables are static in nature
            //so we can access them by using class name 
            Console.WriteLine(ConstExample.number);

            //We can also declare constant variable within a function
            const int no = 10;
            Console.WriteLine(no);

            //Once after declaration we cannot change the value 
            //of a constant variable. so the below live gives error
            //no = 20;

            Console.WriteLine("Press any key to exist.");
            Console.ReadLine();
        }
    }
}
Read-only Variable in C#:
  1. The variable which is created by using the readonly keyword is known as a read-only variable in C#. The read-only variable’s value cannot be modified once after its initialization.
  2. It is not mandatory or required to initialize the read-only variable at the time of its declaration like a constant. You can initialize the read-only variables under a constructor but the most important point is that once after initialization, you cannot modify the value of the readonly variable outside the constructor.
  3. The behavior of a read-only variable is similar to the behavior of a non-static variable. That is, it maintains a separate copy for each object. The only difference between these two is that the value of the non-static variable can be modified from outside the constructor while the value of the read-only variable cannot be modified from outside the constructor body.
  4. A constant variable is a fixed value for the complete class whereas a read-only variable is a fixed value but specific to one object of the class.
Example: Read-only Variable in C#

Let us understand the readonly keyword in C# with an example. Please have a look at the following example. As you can see in the below code, within the ReadOnlyExample class, we declare a readonly variable i.e. public readonly int number = 5; and within the program class Main method we access the readonly variable by using the object of the ReadOnlyExample. This is because readonly variables are non-static by default and as non-static it requires an object instead.

namespace ReadOnlyDemo
{
    class ReadOnlyExample
    {
        public readonly int number = 5;
    }

    class Program
    {
        static void Main(string[] args)
        {
            ReadOnlyExample readOnlyInstance = new ReadOnlyExample();
            Console.WriteLine(readOnlyInstance.number);
            
            Console.WriteLine("Press any key to exist.");
            Console.ReadLine();
        }
    }
}

In the above example, the read-only variable is assigned with a value at the time of its declaration and is accessed using the instance of the class rather than using the class name as read-only variables are non-static in nature. Suppose, you may have another instance of the class, which might have the read-only number variable assigned to a different value based on some conditions. Can I do it? Yes, because the read-only variables are known at runtime.

Example: Read-only Variable Initialization through Constructor in C#

In the below example, we are initializing the readonly variable through the class constructors. You can directly initialize the readonly variables at the time of declaration or you can initialize through class constructors. Once initialized then you cannot change the value of readonly variables in C#.

namespace ReadOnlyDemo
{
    class ReadOnlyExample
    {
        //You can initialize at the time of declaration
        public readonly int number = 5;

        //You can also initialize through constructor
        public ReadOnlyExample()
        {
            number = 20;
        }
        public ReadOnlyExample(bool IsAnotherInstance)
        {
            number = 100;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ReadOnlyExample readOnlyInstance = new ReadOnlyExample();
            Console.WriteLine(readOnlyInstance.number);

            // You cannot change the value of a readonly variable once it is initialized
            // readOnlyInstance.number = 20;

            ReadOnlyExample readOnlyAnotherInstance = new ReadOnlyExample(true);
            Console.WriteLine(readOnlyAnotherInstance.number);

            Console.WriteLine("Press any key to exist.");
            Console.ReadLine();
        }
    }
}
Output:

Const and Read-Only in C#

As you can see in the above output, different values coming out of the program’s output for the two different instances of the class. Hence it proves that read-only variables are also immutable values that are known at runtime and do not change their values for the life of the program.

Let us understand Const, Readonly, Static and non-static variables with one example:
namespace ReadOnlyConstDemo
{
    class Example
    {
        int x; //Non-static variable
        static int y = 200; //Static Variable
        const float PI = 3.14f; //Const Variable
        readonly bool flag; //Readonly Variable
        public Example(int x, bool flag)
        {
            this.x = x;
            this.flag = flag;
        }
        static void Main(string[] args)
        {
            Console.WriteLine(Example.y);
            Console.WriteLine(Example.PI);
            Example obj1 = new Example(50, true);
            Example obj2 = new Example(100, false);
            Console.WriteLine(obj1.x + " " + obj1.x);
            Console.WriteLine(obj2.flag + " " + obj2.flag);
            Console.WriteLine("Press any key to exist.");
            Console.ReadLine();
        }
    }
}
OUTPUT:

Const and Read-Only in C#

In the next article, I am going to discuss the Properties in C# with examples. Here, in this article, I try to explain Const and Read-Only in C# step by step with some examples. I hope you understood the need and use of Const and Read-Only in C#.  Please give your valuable suggestions about this article.

4 thoughts on “Const and Read-Only in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *