CSharp - const vs. readonly


C# supports two special keywords: const and readonly.

both of them try to prevent the modification of a field.

We can declare constants like a variable.

const values cannot be changed after the declaration.

We can assign a value to a readonly field during the declaration or through a constructor.

To declare a constant variable, prefix the keyword const before the declaration.

constants are implicitly static.

readonly values can be both static and non-static; whereas constants are always static.


using System;

class Program//w ww  .j ava 2  s .  c om
    static void Main(string[] args)
        const int MYCONST = 100;
        //Following line will raise error
        Console.WriteLine("MYCONST={0}", MYCONST);


for readonly, we will get errors for these lines:

public  readonly int myReadOnlyValue=105;
//Following line will raise error

Related Topic