157 recommendations for writing high-quality code to improve C # programs--Recommendation 93: Construction methods should initialize primary properties and fields

Source: Internet
Author: User

Recommendation 93: Construction methods should initialize primary properties and fields

The properties of the type should be initialized before the construction method call is complete. If the field does not set an initial value in the initializer, it should be initialized in the constructor method.

Once a type is instantiated, it should be considered as having complete behavior and attributes.

    classCompany {Employee Speciala=NewEmployee () {Name ="Mike"};        Employee Specialb;  PublicEmployee CEO {Get;Set; }  PublicCompany () {CEO=NewEmployee () {Name ="Steve"}; Specialb=NewEmployee () {Name ="Rose"}; }    }

In the construction method, you must first assign a value to the CEO. As long as there is a company entity, it will first have a CEO. The initialization of the Speciala is as follows:

New " Mike "};

The above shows a field initialization. In fact, the initializer also belongs to the compiler's syntax sugar, which is compiled and executed at the very beginning of the construction method. In other words, the initializer can be understood as part of the construction method.

The other reference type fields of the type should also be initialized in the constructor, such as Specialb, because it is not confusing because it is null when it is necessary to ensure that the field is used elsewhere in the type.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 93: Construction methods should initialize primary properties and fields

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.