[. NET Framework programming] Chapter 8 constants and fields

Source: Internet
Author: User

Chapter 8Constants and fields

I. Constants

1. The following types can be defined as constants:

2 primitive types: Boolean, Char, byte, sbyte, decimal, int16, int32, uint16, uint32, int64, uint64, single, double

2 string: String

2 Enumeration type

2. constants are directly embedded into the Il code after compilation. Therefore, constants in one module cannot be obtained by another module at runtime, the changes made to Constants by the former cannot be perceived by the other module at runtime. Therefore, read-only fields should be used to obtain "constant values" during runtime.

 

2. Fields

1. All fields (including static, instance, or read-only fields) are allocated memory at runtime.

2. the read-only field can only be assigned a value in the constructor. (It can also be directly assigned a value when declared. It is not allowed in other places. It is actually equivalent to assigning a value in the constructor ), the static read-only field is assigned a value in the Type constructor, And the instance read-only field is given a value in the instance constructor.

3. Static read-only fields can only be accessed by type names, but cannot be accessed by instance reference.

 

Iii. Differences between static read-only fields and constants:

1. constants are directly embedded into the Il code at the time of compilation, and cannot be re-read at runtime. Static read-only fields can be re-read at runtime.

2. constants can only be assigned values in the declaration, while static read-only fields can be assigned values in the constructor.

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.