Difference between constant, readonly and static in C#

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class.

Constant
Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.

void Calc(int k)
{
 const int i = 10, j = 50;
 const int x = i + j; //no error
 const int a = x + k; //gives error
}

ReadOnly
A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.

Static
The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

Summary:

1. Constants are known at compile time, Read only variables are known at run time.
2. Constants can be assigned values only at the time of declaration, Read only variables can be assigned values either at runtime or at the time of instance initialization via constructor

Comments

Popular