What is Constant variable?
- Compile time constants (const)
- Runtime constants (Readonly)
Compile time constants
- Its must to assign value at the time of declaration.
- const only allow constant variables into the expression.
- Constants can be declared at class level as well as inside the method.
- Constants cannot be declared using the static keyword because they are by default static.
- Constants are an absolute constant which value can no be changed or assigned at the run time.
- Constant variable are a compile-time constant variable.
When to use Const?
Runtime constants (Readonly)
- The Readonly can be declared only at the class level, not inside the method.
- Readonly cannot be declared using the static keyword because they are by default static.
- The Readonly constants value can be set through a reference variable.
- Readonly constant variable is runtime time constant variable.
When to use Readonly?
- The const fields have to be initialized while declaration only, while Readonly fields can be initialized at declaration or in the constructor.
- The const variables can be declared in methods, while Readonly fields cannot be declared in methods.
- The const fields can be used with a static modifier, while Readonly fields cannot be used with a static modifier.
- The const field is a compile-time constant, the Readonly field can be used for run-time constants.