Reputation: 2982
For some reason it seems wrong to me to initialize a class member at declaration like this:
Class Foo
private _bar as New List(Of String)
Public Sub New()
End Sub
End Class
This seems "better":
Class Foo
private _bar as List(Of String)
Public Sub New()
_bar = New List(Of String)
End Sub
End Class
This question says there is no difference. Is one way better than the other (better readability, hidden gotchas, Etc.)?
Upvotes: 2
Views: 2510
Reputation: 10895
Objectively, I prefer the constructor, because the constructor's duty is to initialize all relevant members.
The member itself is too dumb to know when he should live. It's like giving birth, the baby doesn't decide when to be born. The mother (constructor) knows when the time has come!
The moment you create a new instance of a class, the members are declared first and after the constructor (At least the debugger is stepping this way)
So if you have this class:
Public Class Test
Private test1 as List(Of Integer)(New Integer() {1, 2})
Public Sub New()
test1 = new List(Of Integer)(New Integer() {3, 4})
End Sub
End Class
The test1 will contain 3 and 4, after instintiating it.
Also it is more readable if you have lots of members in a class.
Upvotes: 2
Reputation: 195
I asked myself that question a few times when creating new classes. Having found no real difference between the two, I now initialize everything on declaration unless parameters are involved, and only then use the constructor. After all, the constructor can override the declaration values, so it doesn't have to be one or the other.
Also, back then I was also influenced by this old article that mentions how variables need to be initialized for databinding to work, and the working example used initialization in declaration, but in modern versions of Visual Studio/.NET framework this doesn't seems to make any difference anymore.
At the end of the day it seems a matter of preference, and for me initializing on declaration means less lines, which means the code is more readable.
Upvotes: 0
Reputation: 1976
I catch myself using both methods to do this, though if it is a class that will have a large number of constructors and a large number of members, I don't want to have to remember to set each and every variable in every constructor, so in that case I would prefer to declare the value using
public class test
private test1 as list(of String) = new List(of String)
public sub new()
End sub
End class
But I think it all boils down to preference
Upvotes: 0