What are the differences between const and readonly?

const:

  • const creates constants whose value doesn't change over time
  • const variables are static by default
  • variables are needed to be initialized and not assigned anywhere
  • only ValueTypes can be made const variables

readonly:

  • readonly creates fields whose value can be assigned only under constructor
  • these are not static types
  • these can be just declared, but can only be assigned in constructor
  • readonly variables can be ReferenceTypes
  • readonly variables can only Instance fields and can't be local variables

const:

  • const creates constants whose value doesn’t change over time
  • const variables are static by default
  • variables are needed to be initialized and not assigned anywhere
  • only ValueTypes can be made const variables

readonly:

  • readonly creates fields whose value can be assigned only under constructor
  • these are not static types
  • these can be just declared, but can only be assigned in constructor
  • readonly variables can be ReferenceTypes
  • readonly variables can only Instance fields and can’t be local variables
Default image
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply