Const vs Readonly in C#

Constant indicates that it is going to be fixed or remain same throughout the life span(it is more likely to #define Macro in C language), hence -

  1. User defined data types can’t be constant ( i.e. Only primitive data-type can be declared as constants. And, the only possible values of reference types are string and a null reference).
  2. Value must be computed/available at compile time. (i.e. It must be initialized at declaration) 
  3. This also means that if we change the value of const field then consumer solutions (clients) must be build again.
    This also means that a const can’t be used with non-constant expressions. eg. If a field whose value will be computed is being operated with const field would through compile time exception.
    const int num1 = 10;  //value will computed at compile-time
    int num2;  //value will computed at runtime
    const int result = num1 + num2;  //compile time exception will be thrown.
    In short, when an expression references a constant, the value of constant is obtained at compile time only. If expression is referencing Readonly field then the value of field is obtained at runtime.

  4. It can’t changed throughout the life-span. (i.e. Constructors can’t modify)
  5. It is implicitly static.  (i.e. Static modifier can’t be applied on const)
  6. It is treated as a member of class that represent a constant value, it means it can be marked public, protected, internal protected and private.
  7. It is faster because values are inserted directly into the locations where  it has been used. (No method calls is required )  We can say, const value is embedded with MSIL and thus there is no hurdle of allocating memory space at runtime. 
  8. It can be declared in methods
  9. Every dependent assembly gets their local copies of const value.
  10. It can be used in Attributes.
  11. It is marked as "Literal" in MSIL (Readonly is marked as "initonly")

Readonly fields are enough capable to hold complex data types.

It can be initialized at the time of declaration or in constructor. It means Readonly fields can have different values depending upon the constructor used.

Readonly fields can be declared in mehtods.

Readonly values can be changed using Reflection.

And most importantly they are not implicitly static.

So, which one should be used when ?

If your consuming client is in different assembly then better to use Readonly with Static modifier. Read: Shoot-Yourself-In-the-Foot!  It will save time in case you make changes in values as it will not require rebuild. If it is really a constant then constant will be good pick. Note that wherever a constant has been used is just replaced with actual value at compile time only and thus it is very faster.

Join Us!   @CodePattern