Static readonly vs const

2018-12-31 06:19发布

I've read around about const and static readonly fields. We have some classes which contains only constant values. Used for various things around in our system. So I am wondering if my observation is correct:

Should these kind of constant values always be static readonly for everything that is public? And only use const for internal/protected/private values?

What do you recommend? Should I maybe even not use static readonly fields, but rather use properties maybe?

标签: c# constants
15条回答
宁负流年不负卿
2楼-- · 2018-12-31 07:09

Some other things

const int a

  • must be initialized
  • initialization must be at compile time

readonly int a

  • can use default value, without initializing
  • initialization can be at run time
查看更多
笑指拈花
3楼-- · 2018-12-31 07:11

const:

  1. value should be given upon declaration
  2. compile time constant

readonly:

  1. value can be given upon declaration or during runtime using constructors.The value may vary depend upon the constructor used.
  2. run time constant
查看更多
初与友歌
4楼-- · 2018-12-31 07:13

Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime

Reference: c-sharpcorner

查看更多
登录 后发表回答