Const Vs readonly in C#
Declaration and Initialization
- A constant member is defined at compile time and cannot be changed at runtime.
- A readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.
- A readonly field can have different values depending on the constructor used.
- A readonly field can also be used for runtime constants.
- Constants are accessed as if they were static fields, although they cannot use the static keyword.
- A readonly member is not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
- No Memory Allocated, because const value is embedded in IL code itself after compilation.
- Dynamic memory allocated for readonly fields and we can get the value at run time.
ref or out
- Const field can not be passed as ref or out parameter
- readonly field can be pass as ref or out parameters in the constructor context.
- The value of constant is evaluated at compile time
- The value of readonly is evaluated at run time
- The value is constant for all objects
- The value may be different depending upon constructor used (as it belongs to object of the class)