C # constants and fields

Source: Internet
Author: User

Its value is determined during compilation. The compiler saves constants to the Assembly metadata. All primitive types recognized by the compiler can only be constants.

A constant is regarded as a part of a class and is used to see static members.

The code references a constant symbol. It searches for the symbol in the metadata of the defined constant, extracts it, and embeds it into the code. The generated IL contains the value itself.

The const keyword is used in c.

Field: a data member can accommodate any data type. You can only store the primitive type as a constant.

CLR supports type fields and instance fields

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

The class object is created when the type is loaded to an AppDomain.

This is usually the first JIT compilation of any method that references this type.

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

Because fields are stored in the dynamic memory, their values are obtained at runtime. The field solves the version control problem of constants.

CLR supports readonly 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 the constructor method, that is, when the object is first created.

The compiler and verification mechanism ensure that the readonly field is not written outside the constructor.

Allow inline initialization syntax in c # to initialize class fields. C # The field is initialized in the constructor. The Inline code is just a syntactic sugar.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.