Constant vs ReadOnly in C#

Constant vs ReadOnly in C#

Constant vs Readonly in C#

Constant and Readonly keywords are used to assign fix value to variable through out the application, which could not be changed.

Constant in C#

Constant field or variable must be assigned at declaration time and after that it would not be changed or modified. By default constant is static, so constant would not be defined as Static.

Constant field or variable is also known as  immutable value, which is know at compile time and couldn’t change in runtime.

Example 1: 

public const int iConst = 10;

Example 2:

void Manipulate(int c)
{
 const int a = 10, b = 50;
 const int d = a + b; //no error, as evaluated a compile time
 const int e = a + c; //gives error, as evaluated at run time
}

Example 3:

const ClassName objClassName = null;//no error, cause evaluated a compile time
const ClassName objClassName = new ClassName();//gives error, cause evaluated at run time

Readonly in C#

Readonly field or variable could be assigned at runtime, once it will be assigned could not be changed through out the application.

Example 1:

class ClassName
{
 readonly int X = 10; // initialized at the time of declaration
 readonly int X2;
 
 public ClassName()
 {
   X2 = 20; // initialized at run time
 }
}

Readonly keyword can be applied to value type and reference type (which initialized by using the new keyword) both. Note, delegate and event could not be readonly.

Leave a Reply