String level constants and string method level constants

Is there any significant difference between class string constants and level string constants. Will the compiler recognize constants and apply constant folding? Or will an nw object be created?

Here is an example: const-const class

class A { private const string Sid = "sid"; private const string Pid = "pid"; public void Do() { Console.WriteLine(Sid); Console.WriteLine(Pid); } } 

Method Level Constants:

 class B { public void Do() { const string Sid = "sid"; const string Pid = "pid"; Console.WriteLine(Sid); Console.WriteLine(Pid); } } 
+4
source share
2 answers

String constants are newer than "inlined" * because they are true objects. The compiler will always combine parts of the same string constant added together (that is, "A" + "b" is identical to specifying "ab").

String constants can also β€œintern” - all constants of the same value refer to the same actual string object (as far as I know, the C # compiler always does this).

Numeric constants can be "embedded" in those places where they are used in addition to always calculated as much as possible at compile time (i.e. 2 * 2 * 4 is identical to job 16).

To achieve the behavior of "shared constant" you need to use readonly fields instead of const .

* "inline" as placed in the resulting code directly instead of referencing a public value.

0
source

The difference between constants in scope is the same as with the non-constant declaration, the main thing is to consider where these values ​​can be obtained from. Now, which declaration is cleaner, it does not matter to be worthy of an epic war of fire ...

+1
source

All Articles