Constant and ReadOnly in C#

 

Constant:

 

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.

 

For example:

 

public class MyConstClass

{

  public const double PI = 3.14159;

}

 

PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.

 

  •   Constants are static by default
  •   Constant value is evaluated at compile time only
  •   Constants can be Initialed at declaration only
  •   Constants must be a value type , an enumeration, a string literal, or a reference to null
  •   Constants can be marked as public, private, protected, internal, or protected internal

 

 

ReadOnly:-

 

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared

 

For example;

 

public class MyClass

{

  public readonly double PI = 3.14159;

}

 

OR

 

public class MyClass

{

  public readonly double PI;

 

  public MyClass()

  {

    PI = 3.14159;

  }

}

 

  •   A readonly member can be either an instance member or static.
  •   A readonly member value is evaluated at run time in constructor.
  •   A readonly member can be either initialized in declaration or in the constructor.
  •   A readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
  •   A readonly member can hold a complex object by using the new keyword at initialization.