Resharper always suggesting me to make const string instead of string

后端 未结 4 2403
挽巷
挽巷 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: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.

提交回复
热议问题