Why does the compiler store constant values in the assembly metadata? Are they directly embedded to Intermediate Language code from the assembly metadata?
The best way to think about it I find is: At compile time a const is converted to a literal where it is used.
The only reason it goes into the manifest in the assembly it was defined in was to make it accessible to consumers. It is a part of a given type and that type's metadata is stored in it's assembly, not the assemblies that consume it.
So, it is an in-line literal in consumption, and a consumable type-encapsulated property or field in metadata.
I researched myself for quite long time and found from a book that this can be the reason...
Since constant values never changes, constants are considered to be part of the defining type. Therefore defining constants creates metadata.
I think you mix up two assemblies.
The constant is only stored in the metadata in the assembly where it is defined. Metadata contains information about all the types and members in an assembly and constants are members.
No information about the constant is stored in the assembly where it is used. The constant value is used directly in the IL just as if you had written the constant number or string directly in the source.
An example: One of my applications use a lot of constants to identify database tables and fields. I have one assembly that only contain all constants.
When I build the application I add a reference to the "constants" assembly in Visual Studio. Since the assembly only contain constants there is no reference to it in my application and the "constants" assembly is not needed at run-time.
Constants are known at compile time and then they are stored in assembly's metadata. This means that you can only define constants for primitive types.
Yes they are directly loaded from metadata. There would be no memory allocation at runtime.