Basic of C# - Const and Readonly

The first difference we need to know about const and read-only.

Const variable in C#

Const variable is immutable and it is known when the program compilation is happening, and does not change the value for the lifetime of the program.

The read-only variable is also immutable, and it is known when the program is at runtime; it also does not change the value for the lifetime of the program.

When you declare a variable with a const keyword, it is immutable after declaration. and since const is known to program when it's compiling it is mandatory to give value to const. If you do not assign a value to a const variable it will give an error.

const int one = 1; // will not give you error
const int two; // not assigning value will give you error.

When you declare a constant variable with a value, it is a static value by default. When you declare a variable using a read-only keyword, it is also an immutable variable after initialization. This means it does not have to be declared at the time of compiling, they can be constructed under the constructor, which means we can only modify read-only variables inside the constructor.

If the class was created more than once, each time when the class is instantiating, the read-only also gets declared.

namespace BasicCsharp
{
    class className
    {
        readonly int numb;
        public className(int numb)
        {
            this.numb = numb;
        }
        static void Main(string[] args)
        {
            className obj1 = new className(100);
            Console.WriteLine($"{obj1.numb}");
            className obj2 = new className(300);
            Console.WriteLine($"{obj2.numb}");
        }
    }
}

The outcome of this code is
100
300

like you can see in the code above. read-only does not initialize on the compile time it waits till runtime and it can get initialized multiple times in the constructor of the class

The main difference between const and read-only is that const is a fixed value for the whole class while read-only is only fixed for a specific instance of class.

Next Recommended Reading const and readonly