Why are const
usages replaced by their values on compile time but then still included in the assembly? At least this is what IL DASM and Reflector shows.
Currently I am using const
for defining many magic numbers and strings to easier be able to change code without affecting run-time performance.
Now I know that that doesnt affect the used memory but it still affects compiled assembly size which is crucial for example for mobile phone apps.
Another disadvantage is that other people easier understand magic numbers when looking at the disassembled code.
I am really interested in why the compiler (Mono as well as .NET) does this exactly?
This behaviour is specified in the ECMA-335 standard (of which both .NET and Mono are implementations). Citing from section II.22.9, "Constant":
Note that
Constant
information does not directly influence runtime behavior, although it is visible via Reflection (and hence can be used to implement functionality such as that provided bySystem.Enum.ToString
). Compilers inspect this information, at compile time, when importing metadata, but the value of the constant itself, if used, becomes embedded into the CIL stream the compiler emits. There are no CIL instructions to access theConstant
table at runtime.
That is, const
values are "inlined" (possibly because they can be, and for performance reasons), but are kept in metadata nevertheless so they can be inspected by compilers and tools.
If no metadata were emitted for the const
-ness of fields, this would have these consequences (possibly among others — these are just two examples):
const
fields.System.Reflection
, you would no longer be able to use the FieldInfo.IsLiteral
property.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With