The constant name is "constant", that is, its value will never change. When defining a constant symbol, its value must be determined during compilation. After compilation, the constant value is saved inProgramSet (assembly) metadata, which means it must be the base metadata that the compiler can process (primitive type ). In C #, the constants can be defined as boolen, Char, byte, sbyte, int16, uint16, int32, uint32, int64, uint64, single, double, decimal, and string.
Constants are always treated as static members rather than instance members. Defining constants will produce metadata.
UsingSystem;Public Sealed ClassSomelibrarytype {Public ConstInt32 maxentriesinlist = 50 ;}
AboveCodeNote that C # does not allow you to specify the static keyword for a constant, because a constant usually implies static.
When the code references a constant symbol, the compiler searches for the symbol in the metadata of the Assembly that defines the constant, extracts the value of the constant, and embeds the value into the compiled il code. Because the constant value is directly embedded into the code during compilation, you do not need to allocate any memory for the constant during runtime.
In addition, we cannot get the constant address or pass the constant through reference. As a result, constants do not have a good cross-assembly version control feature.
Let's take a look at why the constant version control problem occurs. Define a constant I = 50 in assembly a and compile it to get an assembly. At this time, assembly B References Assembly A and uses the constant I in A. When we compile assembly B, the compiler reads the value of I in a 50, put it directly to the place where I appears in B. That is to say, after B is compiled, B only knows the number 50, but does not know how to obtain it. In this case, we revise Assembly A and change its I to 1000, then we compile assembly a to get the new Assembly A, but our B does not know that the 50 has changed, so if B wants to get the new value, it must be re-compiled.
Therefore, at runtime (not during compilation), if one assembly requires a value from another assembly, constants cannot be used and read-only fields should be used.