(For some reason OE is no longer putting a > in col. 1 of the post I am
replying to. You'll find my reply appended below following the ===s.)
Apparently Google is screwing around with their message formatting
again (I post exclusively through groups.google.com)!
Can you elaborate a bit. When you say "must" ... does that mean that Iwill
see a compiler error if I violate the rule?
Nope, you would just end up with some uninitialized variables.
Also, when you say "chain" do
you mean what I'll call a strict chain in which if I have n+1 constructors,
0-n, the sequence will always be 0 or 1,0 or 2,1,0 or 3,2,1,0 or ... or
n,n-1,...,0?
Nope, no calling order is enforced.
It's more of a DRY (don't repeat yourself) thing than anything. It
would be bad design (imo) to have the same variable initialization
routines in every constructor, so you basically have two options.
First is to have a sub routine that does the initialization, this sub
routine would need to be called by every constructor (better, but
still bad). The second option would be to have one root constructor,
usually parameterless and private if need be, that does the
initialization and then all other constructors (where it makes sense)
call into that one, either directly or through a chain.
For example, consider this class's constructors:
//////////////
Public Class Report
Private Sub New()
_CreatedDate = DateTime.Now()
End Sub
Public Sub New(creator As String)
'// Initializes CreateTime
Me.New()
_Creator = creator
End Sub
Public Sub New(creator As String, createdDate As DateTime)
'// Custom initialization, no constructors called
_Creator = creator
_CreatedDate = createdDate
End Sub
Public Sub New(reportToClone As Report)
'// Break down complex object into another constructor call
Me.New(reportToClone.Creator, reportToClone.CreatedDate)
End Sub
End Class
/////////////
That should demonstrate several ways constructor chaining would be
desirable, and a few where it wouldn't be.
I also forgot to weigh in on the original question. Personally, I
always initialize the local variable directly and rarely through the
constructor (unless of course the values are being passed in).
Thanks,
Seth Rowe [MVP]
http://sethrowe.blogspot.com/