I usually code something like this:
public class Monkey { private int id = 0; private String name = ""; private SomeReferenceType someReferenceType = null; private SomeOtherReferenceType someOtherReferenceType = null; public Monkey() { this.Initialize(); } public void Initialize() { this.someReferenceType = new SomeReferenceType(); this.someOtherReferenceType = new SomeOtherReferenceType(); } }
A simple class... something I would do out of habit. Helps keep the constructor clean, modular, and easy to read. (I hate constructors with 50+ lines of code all over the place. It's simply bad form.) I can wrap my reference type initializations in a try/catch in the Initialize() method, if needed, and I can cleanly add other initialization methods such as RegisterEvents().
try/catch
Initialize()
RegisterEvents()
Essentially what I'd like to point out here, however, is that I don't usually instantiate reference types in-line. I find it more clear to do it from a constructor, or better yet, an Initialize() method, where it's clear that there's 'more work' being done to instantiate these reference types.
I would probably do the same for Type constructors, however the 'Design Guidelines' tells me not to: "Consider initializing static fields inline rather than explicitly using static constructors because the CLR can optimize the performance of types that do not have an explicitly defined static constructor."
So as the example points out, for STATIC constructors, this is bad...
public class BadStaticExample { static Guid runId; static BadStaticExample() { runId = Guid.NewGuid(); } // Other members... }
...and this is good...
public class GoodStaticExample { static Guid runId = Guid.NewGuid(); // Other members... }
And I don't know why, but this is just funny: "Consider using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construction of a new instance, or if following the constructor design guidelines feels unnatural."