Readonly and const variable c#

 

In C#, both readonly and const are used to create fields whose values cannot be changed after initialization. However, there are crucial differences between them.

 

const (Compile-Time Constant):

  • Initialization: const fields must be initialized at the time of their declaration. You cannot leave a const field uninitialized and set its value in a constructor.
  • Compile-Time Evaluation: The value of a const field must be a constant expression that can be fully evaluated at compile time. This means you can only assign primitive types (like int, float, bool, char, string), enums, or null (for reference types other than string) that are known at compile time. You cannot assign values that are determined at runtime (e.g., values from other variables, method calls, DateTime.Now).
  • Implicitly Static: const members are implicitly static. You don't need to (and cannot) use the static keyword when declaring a const field.
  • Scope: const can be declared at the class level or within a method (as a local constant).

 

 


readonly (Runtime Constant - Modified in Constructor):

  • Initialization: readonly fields can be initialized either at the time of their declaration or within the constructor(s) of the same class.
  • Runtime Evaluation: The value of a readonly field can be assigned using expressions that are evaluated at runtime. This allows you to initialize readonly fields with values that are not known until the object is created, such as values passed as constructor parameters or values obtained from runtime operations.
  • Instance or Static: readonly fields can be either instance members (associated with each object of the class) or static members (associated with the class itself). You explicitly use the static keyword for static readonly fields.
  • Scope: readonly can only be declared at the class level (as a field). Local variables cannot be readonly.

 

 


Related Question