Declaring strings public static readonly versus public const versus public static const

后端 未结 5 1671
故里飘歌
故里飘歌 2021-02-01 02:47

In each project we have there is a file used to store the various SQL statements used in that project. There are a handful of variations on how the class is declared and how the

5条回答
  •  误落风尘
    2021-02-01 03:22

    You should choose an access modifier (public or internal) based on which code uses the strings.

    • static const is a compiler error.

    • A static readonly field is a normal field which cannot be set after the static ctor.

    • A const string will be replaced by its literal value at compile time.
      Therefore, it will give slightly better performance (since the runtime doesn't use the field).
      However, since it's substituted at compile-time, any changes to the definition in one assembly will not be picked up by other assemblies until they're all recompiled.

    If your code is only used in one assembly, you might as well use const strings.
    However, if your strings are used by other assemblies (or might be in the future), you should use static readonly strings for maintainability.

    Also note that a const string is a compile-time constant.
    If you need to incldue things like the machine name or username in the string, you need to make it static readonly.

提交回复
热议问题