Resharper always suggesting me to make const string instead of string

后端 未结 4 2314
挽巷
挽巷 2021-02-20 13:38

which one is good:

string sQuery = \"SELECT * FROM table\";

or

const string sQuery = \"SELECT * FROM table\";
<
相关标签:
4条回答
  • 2021-02-20 14:14

    If the string never changes and is never used outside your assembly, then const is a good idea. If it never changes but is used outside your assembly, static readonly might be a better idea -- consts are "burned in" at the site of the call, not stored in one location, so recompiling the assembly that contains the const does not update the dependent assemblies -- they have to be recompiled too. static readonly variables on the other hand do get updated in dependent assemblies.

    0 讨论(0)
  • 2021-02-20 14:26

    ReSharper only suggests this if the particular string reference never changes. In that case you express your intend by using const string instead of just string.

    0 讨论(0)
  • 2021-02-20 14:28

    The latter is better - it means that:

    • This isn't an instance variable, so you don't end up with a redundant string reference in every instance that you create
    • You won't be able to change the variable (which you presumably don't want to)

    There are some other effects of "const" in terms of access from other assemblies and versioning, but it looks like this is a private field so it shouldn't be an issue. You can mostly think of it as being:

    static readonly string sQuery = ...;
    

    In general I believe it's a good idea to make fields static when you can (if it doesn't vary by instance, why should it be an instance variable?) and read-only when you can (mutable data is harder to reason about). Let me know if you want me to go into the details of the differences between static readonly and const.

    0 讨论(0)
  • 2021-02-20 14:29

    It does this because if you accidentally assign a new value to sQuery in your code, if it's a const you'll get a compile error, so it will catch a bug at compile time. Same with its suggestion to make member variables which are set in the ctor only to be readonly

    0 讨论(0)
提交回复
热议问题