Skip to main content
Source Link
Scott Lawrence
  • 7.2k
  • 13
  • 46
  • 64

One of the team members in our office provided the following guidance on when to use const, static, and readonly:

  • Use const when you have a variable of a type you can know at runtime (string literal, int, double, enums,...) that you want all instances or consumers of a class to have access to where the value should not change.
  • Use static when you have data that you want all instances or consumers of a class to have access to where the value can change.
  • Use static readonly when you have a variable of a type that you cannot know at runtime (objects) that you want all instances or consumers of a class to have access to where the value should not change.
  • Use readonly when you have an instance level variable you will know at the time of object creation that should not change.

One final note: a const field is static, but the inverse is not true.

Post Made Community Wiki by CommunityBot