'Static readonly' vs. 'const'

前端 未结 18 3028
旧巷少年郎
旧巷少年郎 2020-11-22 04:07

I\'ve read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things

18条回答
  •  半阙折子戏
    2020-11-22 04:55

    Constants are like the name implies, fields which don't change and are usually defined statically at compile time in the code.

    Read-only variables are fields that can change under specific conditions.

    They can be either initialized when you first declare them like a constant, but usually they are initialized during object construction inside the constructor.

    They cannot be changed after the initialization takes place, in the conditions mentioned above.

    Static read-only sounds like a poor choice to me since, if it's static and it never changes, so just use it public const. If it can change then it's not a constant and then, depending on your needs, you can either use read-only or just a regular variable.

    Also, another important distinction is that a constant belongs to the class, while the read-only variable belongs to the instance!

提交回复
热议问题