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