const: Can't be changed anywhere.
readonly: This value can only be changed in the constructor. Can't be changed in normal functions.
Example : Below my example which is show diffence between Const and Readonly
We have a Test Class in which we have two variables one is readonly and another is constant.
class Test {
readonly int read = 10;
const int cons = 10;
public Test() {
read = 100;
cons = 100;
}
public void Check() {
Console.WriteLine("Read only : {0}", read);
Console.WriteLine("const : {0}", cons);
}
}
Here I was trying to change the value of both the variables in constructor but when I am trying to change the constant it gives an error to change their value in that block which have to call at run time.
So finally remove that line of code from class and call this Check() function like the following code
class Program {
static void Main(string[] args) {
Test obj = new Test();
obj.Check();
Console.ReadLine();
}
}
class Test {
readonly int read = 10;
const int cons = 10;
public Test() {
read = 100;
}
public void Check() {
Console.WriteLine("Read only : {0}", read);
Console.WriteLine("const : {0}", cons);
}
}