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

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

In C#, what\'s the difference between

static readonly string MyStr;

and

const string MyStr;

?

5条回答
  •  孤城傲影
    2020-12-02 07:11

    OQ asked about static string vs const. Both have different use cases (although both are treated as static).

    Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const fields because you might have base and subclass in different assemblies and private fields are inherited.

    Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).

    If you meant static readonly vs const, then I'd recommend static readonly for almost all cases because it is more future proof.

提交回复
热议问题