Difference between readonly and const keyword in C#

In C#, readonly and const are both used to define immutable values, but they have key differences in how and when their values are assigned.

  1. const (Constant)
  • A const field is a compile-time constant, meaning its value must be assigned at declaration and cannot be changed later.
  • It is implicitly static, so it belongs to the type rather than an instance.
  • The value of a const field is hardcoded into the compiled code, so changes require recompilation.
  • Only primitive types, enums, and string can be const.

Example of const:

Example. Pi is a compile-time constant and cannot be changed.

  1. readonly (Read-Only Field)
  • A readonly field can be assigned only during declaration or in the constructor, making it a runtime constant.
  • It is not implicitly static, so each instance can have different values.
  • Unlike const, readonly fields can hold reference types and mutable objects (though the reference itself remains immutable).
  • It is evaluated at runtime, meaning it can be set dynamically based on constructor parameters.

Example of readonly:

Each instance of Example can have a different number value.

Key Differences:

Featureconstreadonly
AssignmentOnly at declarationAt declaration or in constructor
MutabilityCannot change after compilationCan be assigned per instance in the constructor
StorageStored as a literal in compiled codeStored in memory like normal fields
Type SupportOnly primitive types, enums, and stringsAny data type (value or reference)
Instance vs. StaticAlways staticCan be instance or static
Runtime EvaluationNo (compile-time only)Yes (runtime assignment allowed)

When to Use Which?

  • Use const when the value is truly constant (e.g., mathematical constants like Pi, conversion factors).
  • Use readonly when the value can be determined at runtime (e.g., configuration settings, object references).

Leave a Reply

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

Protected with IP Blacklist CloudIP Blacklist Cloud

This site uses Akismet to reduce spam. Learn how your comment data is processed.