'const string' vs. 'static readonly string' in C#

前端 未结 5 1942
臣服心动
臣服心动 2020-12-02 06:39

In C#, what\'s the difference between

static readonly string MyStr;

and

const string MyStr;

?

5条回答
  •  -上瘾入骨i
    2020-12-02 07:11

    When you use a const string, the compiler embeds the string's value at compile-time.
    Therefore, if you use a const value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.

    A static readonly string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.

    This also means that a static readonly string can use non-constant members, such as Environment.UserName or DateTime.Now.ToString(). A const string can only be initialized using other constants or literals.
    Also, a static readonly string can be set in a static constructor; a const string can only be initialized inline.

    Note that a static string can be modified; you should use static readonly instead.

提交回复
热议问题