What is the difference between new
in a constructor and new
in a member declaration?
Example
public class PspGame {
private List<string>name = new List<string>();
private List<string>_value;
public PspGame() {
_value = new List<string>();
}
}
What is the best way to do it and are there any performance issues?
The main purpose of constructors is to set the initial state of an object, when the object is created by using the new operator. Constructor declarations are very much like method declarations.
Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
The default constructor does not initialize members of your class.
They're pretty much equivalent (any differences in terms of performance and memory usage are negligible). The only real difference is that when you do:
private List<string>name = new List<string>();
...the assignment always happens no matter what constructor is used to create an instance of the object. When you do the assignment within a constructor, then it only happens when that specific constructor is used.
So if you have multiple constructors but you always want to initialize name
exactly the same way, it is a bit shorter to use the first form than to explicitly initialize it in each constructor.
As a general rule, however, I prefer initializing fields in the constructor implementations, even if it does make the code more verbose in some cases.
Having an argument in the constructor (non-default constructor), for me, allows for better testing. You can 'inject' certain data into a member field that you wouldn't necessarily be able to do without making that member public (or at least internal) or making a second call with a 'setter' property.
Because you can have multiple constructors, you could have a second one for testing, in conjunction with a default constructor, if you really wanted.
There aren't any real performance issues other than having to make a separate call to populate data later, or having less-maintainable code with multiple calls to the class (one to create the object, the second to populate the member).
EDIT: I realized I sorta answered the wrong question. I thought he was asking about the difference between default and non-default constructors. Now I see it was about a default constructor that initializes the member in the constructor vs. in member declaration...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With