Question Default value at declaration or in constructor?

VentureFree

Well-known member
Joined
Jan 9, 2008
Messages
54
Programming Experience
5-10
One would think I'd already know this, but I never really gave it much thought before now. When declaring a member variable for a class, is it better to set the default value at the declaration
VB.NET:
Private m_strMyVariable As String = ""
Or is it better to do it in the constructor
VB.NET:
Private m_strMyVariable As String

Public Sub New()
    m_strMyVariable = ""
End Sub
Should I maybe always specify a value at declaration, even if it's Nothing, and just override that value in the constructor(s) as needed? Or is it situation specific? If so, a really quick rundown of which situations might warrant which treatment would be nice.
 
It is the same if you use the declaration or the constructor, the compiler moves all such calls to the constructor anyway. I'd say the declarative style is more readable because it doesn't separate the declaration and the assignment. In some cases you have more advanced or conditional calls to set the value, so it may not be possible to do that declarative.
 
In essence I think you're saying that setting default values at the declaration should be preferred when possible, if for no other reason than for readability. Setting it in the constructor should be done only when necessary, or when setting it at the declaration would actually decrease readability (for example, if it required nested IIf calls or something equally ridiculous).

That makes sense to me. Thanks for the clarification.
 
Yeah, at the declaration is my preference too, since it's much harder to miss the instantiation. The other time to set in the constructor is when the order of initialization is important; for example if you instantiate an array with the bounds of another variable. I think VB does instantiations in top-down line order immediately after the base class constructor is called...but again it might not.
 
I've read previously that initialising a field where it's declared can be more greatly optimised by the compiler than initialising it in the constructor. I have no idea of any details though. Regardless, I never see the point of doing in two lines what you can do in one unless it specifically improves readability.
 
Back
Top