Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are C# const members allocated in memory? [duplicate]

The title of the question is self explanatory. I wonder if a member that is declared const is singleton for all instances of the class or each instance has it's own copy.

I've read some questions about const but most of them refer to const variables inside a method.

like image 225
rareyesdev Avatar asked May 07 '14 22:05

rareyesdev


1 Answers

C# constants are implemented as fields with the literal constraint in the Common Language Instructructure. Looking up ECMA-335 §I.8.6.1.2 provides the definitive answer (emphasis mine):

The literal constraint promises that the value of the location is actually a fixed value of a built-in type. The value is specified as part of the constraint. Compilers are required to replace all references to the location with its value, and the [Virtual Execution System] therefore need not allocate space for the location. This constraint, while logically applicable to any location, shall only be placed on static fields of compound types. Fields that are so marked are not permitted to be referenced from CIL (they shall be in-lined to their constant value at compile time), but are available using reflection and tools that directly deal with the metadata.

So there you go, the values of const fields must be copied by compilers directly into the instruction stream (typically using ldc.* instructions). They do not exist in a referencable location, but need to be available in the metadata and via reflection. They could be implemented like static fields, but do not have to.

like image 153
Trillian Avatar answered Sep 25 '22 19:09

Trillian