Reputation: 139
Constants referenced by code are replaced by their actual values when being compiled to IL.
Since public constants can be referenced by code outside of a particular assembly, it makes sense that they are stored in the assembly's metadata.
But why are private constants stored there? There are no references to those constants in the IL of the code in the assembly that defined them, and they aren't exposed to be referenced outside of the assembly.
So what needs to access those values after the code has been compiled?
It seems to me that all constants in assemblies should be public, and private constants should be a language-level feature that simply cause the compiler to emit literal values.
Upvotes: 3
Views: 305
Reputation: 171226
The C# compiler could optimize away all kinds of private stuff. Not just constants. It could remove unused members, classes, code. It could strip away private names. It could delete private properties and replace them with methods. etc.
Reflection access and IL rewriting tools come to mind as important use cases for private stuff. Also, debugging is easier when most meta-data is still present. For example, you can use Edit&Continue to use previously unused members. You can call statically unused members using the Immediate Window.
Maybe there are implications for PDB symbols as well although I cannot think of any right now.
Note, that .NET assemblies contain lots of meta-data that is only useful for reflection access. Attributes have no runtime implications at all other than being inspectable. Assemblies are meant to be rich and self-describing.
One could argue that constants are especially useless to keep because they are always statically unused. That, however does not mean that there are no reflection uses for them. They also can help with decompiling code. A smart decompiler could notice that a certain literal is identical to a constant declared nearby. Furthermore, why make an exception for constants to optimize them away? There are very few constants in typical programs. Even assuming that it would be better to remove them the investment would hardly pay off. Better develop useful language features in the same time.
Upvotes: 4