A ReadOnly field can be initialized either at the declaration time or in the constructor. The ReadOnly fields can have different values depending on the constructor used. The ReadOnly fields can be used for run time constants. It marks the field as unchangeable but the property can be changed inside the constructor of the class.
A Const field can only be initialized at the declaration of the field. The Const fields can be used for compile time constants and it can’t change at run time. In a program where ever we are using Const, then that value will be replaced by the compiler.
public class Test
public const int ConstValue = 10;
public static readonly int ReadonlyValue = 20;
By looking to the above code snippet, we can say ConstValue is declared as literal
and it has an int value assigned to it whereas ReadonlyValue is declared as initonly
and it has not been assigned any value to it.
So we can say that if a type is declared as Const, its value is known as compile time, but when the value that is declared as static readonly field, that cannot be known at compile time.
Asked In: Many Interviews |