What is the difference between Constants and Readonly Property?

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example

Constants

  1. Constants are static by default
  2. They must have a value at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)
  3. Could be declared within functions
  4. Are copied into every assembly that uses them (every assembly gets a local copy of values)
  5. Can be used in attributes

Readonly

  1. Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)
  2. Must have an evaluated value by the time the static constructor is done
  3. It’s not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)

Example

public class Const_Vs_ReadonlyProperty
{
  public const int I_CONST_NAME = 2;
  public readonly int I_RO_NAME;
  public Const_V_Readonly()
  {
     I_RO_NAME= 3;
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *