CSharp - const vs. readonly

Introduction

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.

Demo

using System;

class Program//from w ww. j a  v a2s.  c o m
{
    static void Main(string[] args)
    {
        const int MYCONST = 100;
        //Following line will raise error
        //MYCONST=90;//error
        Console.WriteLine("MYCONST={0}", MYCONST);
    }
}

Result

for readonly, we will get errors for these lines:

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

Related Topic