c constants and fields

  • 2020-05-07 20:19:08
  • OfStack

Its value is determined at compile time. The compiler stores constants in the assembly's metadata, all of which are constants only of primitive types known to the compiler.

Constants are viewed as part 1 of a class, which sees static members.

The code references a constant symbol, looks it up in the metadata where the constant is defined, extracts it, and inserts the code. The generated IL is the value itself.

The const keyword is used in c#.

Field: has 1 type of data member, can hold any data type, not just like a constant 1 can only store primitive type.

CLR supports type fields and instance fields

Type field: the dynamic memory used to hold the field data is allocated in the type object,

Class objects are created when the type is loaded into 1 AppDomain.

This is usually when any method that references this type is first compiled by JIT.

Instance fields: the dynamic memory used to hold the field data is allocated when an instance of the type is constructed.

Because fields are stored in dynamic memory, their values are not retrieved until run time, fields solve the problem of constant versioning.


CLR supports readonly fields and read/write fields

The read and write fields can be changed multiple times in the code.

The readonly field can only be written in constructor methods, that is, when the object is first created.

The compiler and validation mechanisms ensure that the readonly field is not written outside the constructor.

c# allows inline initialization syntax to initialize the fields of a class. c# actually initializes the field in the constructor, and the inline code is just syntax sugar.

Related articles: