What is difference between readonly and const in C#?

(Last Updated On: October 2, 2015)

Answer: Use and conceptual difference between readonly and const in C# with example.

CONST: The constant -const variable cannot be changed once it has been declared and initialized. If we try to change it anywhere in the class, compiler will flash an error at compile time.

Generally, at the time of class design we decide, what field to make const, so, it cannot be changed accidently during writing of class functions.

For example, in a class we may want to have PI =3.14, as a const variable to calculate the area of a circle, as it is not supposed to be changed anywhere in any methods.

 

READONLY: Also, readonly variable cannot be changed anywhere in the class accept class constructor or initializer list( where class fields are declared). If we try to change readonly variable anywhere in the functions of the class, it will flash an error at compile time itself.

Some time we may want to initialized some variable during object creation and don’t want it to be changed anywhere in the class, then, we have to make it readonly.

 

Example with comments: