Friday, 5 June 2015

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 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

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.

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.


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

No comments:

Post a Comment