Difference between string and const string

To explicitly show that it doesn't change, so that when someone reads your code (including yourself) she'll know that this var doesn't change.
The tool probably suggests that for other types of vars as well, if you don't change them later. This is good practice.
Of course if you'll try to change it later, you'll get a compilation error.


Along with what was said by the others. When you declare a local variable with const, the compiler (in release mode) will replace usages of the variable with the const value in IL; resulting in a smaller stack.

Strings specifically are a special case. During compilation, the compiler runs through a string-interning process where the string variable you created may actually point to existing string, or a new one... since strings are immutable, it doesn't usually matter too much. This is not specific to const strings, but rather string literals.

In the example case of const string title = ..., const means that the value is assigned at the time of declaration and it cannot be changed.

This is a related question that may have what you're looking for.

Is there a runtime benefit to using const local variables?


Well, in my opinion the major point in using constant strings is that a constant string is automatically interned. So if you have 1000 instances of a type that has a regular string field and all instances store the same string that will never be changed then 1000 equal string instances will be stored, unnecessarily blowing up the memory profile of your application. If you declare the string constant it will only consume memory once. This is the same behavior as using the string literal directly. In contrast to a static readonly string the value of constant string is stored directly in the referencing class.


const is the prefix of a constant variable. One that doesn't change at runtime.

Usually if you have a variable that meets this you should declare it as constant (const), both to avoid mistakes in the code and to enable compiling optimizations.

This is why the refactoring tool does it for you.

Tags:

C#

Refactoring