Initialization of a member inside or outside the constructor

Which of the two initializations is better?

public class ServiceClass { private DataManager dataManager = new DataManager(); private Dictionary<string, string> stringDictionary = new Dictionary<string, string>(); private Dictionary<string, DateTime> timeDictionary = new Dictionary<string, DateTime>(); public ServiceClass() { //other object creation code } } 

OR

 public class ServiceClass { private DataManager dataManager; private Dictionary<string, string> stringDictionary; private Dictionary<string, DateTime> timeDictionary; public ServiceClass() { dataManager = new DataManager(); stringDictionary = new Dictionary<string, string>(); timeDictionary = new Dictionary<string, DateTime>(); //other object creation code } } 
+4
source share
2 answers

Since you have another code ("code to create another object") in the explicit constructor, I would prefer to put all the initialization there.

+2
source

I would rather use a constructor.

This is due to the fact that we found that objects restored through a serializer (in this case, a data serializer) did not call their field initializers.

In addition, it ensures that all initialization logic is grouped together, and not potentially interleaved throughout the code (wherever you want to define your field variables).

+4
source

Source: https://habr.com/ru/post/1332295/


All Articles