'Static readonly' vs. 'const'

前端 未结 18 2601
旧巷少年郎
旧巷少年郎 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:51

    Const: Constant variable values have to be defined along with the declaration and after that it won't change.const are implicitly static, so without creating a class instance we can access them. This has a value at compile time.

    ReadOnly: We can define read-only variable values while declaring as well as using the constructor at runtime. Read-only variables can't access without a class instance.

    Static readonly: We can define static readonly variable values while declaring as well as only through a static constructor, but not with any other constructor. We can also access these variables without creating a class instance (as static variables).

    Static readonly will be better choice if we have to consume the variables in different assemblies. Please check the full details in the below blog post:

    Const Strings – a very convenient way to shoot yourself in the foot

提交回复
热议问题