There are many different keywords available in C#. This tutorial will look at the differences between the readonly and const keywords in C# and when to use each.
By default, a const is static. In C#, a constant is a value that cannot be changed during the execution or run time of a program. That means value of Const will not change during whole program. It's mandatory to assign a value to it when we declared it.
Readonly in C#
A Readonly field can be initialized either at the time of declaration or within the constructor of the same class. We can also change the value of a Readonly at runtime or assign a value to it at runtime (but in a non-static constructor only).
Difference
Initialization
public const int MaxValue = 100;
public readonly int MaxValue;
public MyClass(int maxValue)
{
MaxValue = maxValue; // Allowed in constructor
}
Value Type
public const double Pi = 3.14159;
public readonly DateTime CreationTime = DateTime.Now;
Scope
public const int MaxValue = 100;
public readonly int MaxValue; // Instance-specific
public static readonly int GlobalValue = 100; // Shared across all instances
Mutability
const
readonly
S.No. | Const | ReadOnly |
---|---|---|
1 | A Const can only initialized at the time of declaration. | A ReadOnly can be initialized at the time of declaration or within the constructor of the same class. |
2 | A Const field is a compile time constant. | A ReadOnly field is used as a run time constant. |
3 | It can be access using classname.constname | It can be access using Instance |
4 | Once a value is assigned to a constant. It can not be initialized again. | You can change ReadOnly value number of times. You can also change it inside constructor. |
5 | Example - public const int MaxValue = 100; | Example - public readonly int MaxValue = 100; |