c# - String constants embedded twice in .Net? -
say have simple (the simplest?) c# program:
class program { static void main() { system.console.writeline("hello, world"); } }
if, compile code , @ resultant .exe, see "hello, world" string in exe image expected.
if refactor code to:
class program { const string greeting = "hello, world"; static void main() { system.console.writeline(greeting); } }
if compile code , @ resultant .exe, see "hello, world" string literal in exe image twice. surprising me. under impression string literals shared, , therefor show in image 1 time. can explain this? perhaps second copy of string needed reflection metadata?
the ecma-335 cli specification sheds light on this. c# const
declared static literal
field in il. section i.8.6.1.2 (emphasis mine):
the literal constraint promises value of location fixed value of built-in type. value specified part of constraint. compilers required replace references location value, , ves therefore need not allocate space location. constraint, while logically applicable location, shall placed on static fields of compound types. fields marked not permitted referenced cil (they shall in-lined constant value @ compile time), available using reflection , tools directly deal metadata.
thus compiler takes constant value , replaces throughout code. not allowed reference constant storage. there, other literal string. gives slot in metadata table , uses ldstr
op code load string. thus, value appears twice in assembly. once in storage location constant, cannot referenced compliant compiler. , time in metadata table.
Comments
Post a Comment