Jon wrote:
> Is there a best practice for how much logic, and what type of logic,
> to place in a C# constructor?
IMHO: as little as possible.
> For example, if I have setup logic that might take 20 seconds to
> several minutes to complete, should that be placed in a C#
> constructor?
20 seconds is a stretch, but in just the right circumstance you might be
able to get away with it. Several minutes? No way.
Use a factory or an initialization method for lengthy
initialization-related operations.
If nothing else, a lengthy operation in a constructor strongly implies
that in the constructor, the object "this" reference is "leaking" like
crazy, which is a big no-no. The "this" reference should not be exposed
to external code until the object is fully constructed.
If the implication is wrong, then that means all that initialization
code had nothing to do with the "this" reference, and so could precede
its existence (e.g. by being executed in a factory method). On the
other hand, if the implication is right, then in theory there's a bunch
of initialization code that really needs a fully-constructed object, in
which case an initialization method could be more appropriate.
> This involves replicating data from a remote service into a local
> database, and so it sometimes is quick, but if there is a large amount
> of data, it could take several minutes to complete.
>
> Are there any good books or web pages that explain C# constructor best
> practices?
I don't know of any. Surely a "good book" would only address this as a
small subset of its content. I suppose a blog entry or other web page
might exist. Google can help you find that.
Of course, wait an hour or so, and this post will be on Google, viewable
as a single web page. Then there will be at least one web page
addressing the question.
Pete