Initialize class fields in constructor or at declaration?

前端 未结 15 2316
南旧
南旧 2020-11-22 01:16

I\'ve been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:



        
15条回答
  •  独厮守ぢ
    2020-11-22 02:00

    Not a direct answer to your question about the best practice but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).

    class MyGeneric
    {
        T data;
        //T data = ""; // <-- ERROR
        //T data = 0; // <-- ERROR
        //T data = null; // <-- ERROR        
    
        public MyGeneric()
        {
            // All of the above errors would be errors here in constructor as well
        }
    }
    

    And the special method to initialize a generic field to its default value is the following:

    class MyGeneric
    {
        T data = default(T);
    
        public MyGeneric()
        {           
            // The same method can be used here in constructor
        }
    }
    

提交回复
热议问题