Information Technology Reference
In-Depth Information
one static constructor, and it must not take any arguments. Because static
constructors are called by the CLR, you must be careful about exceptions
generated in them. If you let an exception escape a static constructor, the
CLR will terminate your program. The situation where the caller catches
the exception is even more insidious. Code that tries to create the type will
fail until that AppDomain is unloaded. The CLR could not initialize the
type by executing the static constructor. It won't try again, and yet the type
did not get initialized correctly. Creating an object of that type (or any
type derived from it) would not be well defined. Therefore, it is not
allowed.
Exceptions are the most common reason to use the static constructor
instead of static initializers. If you use static initializers, you cannot catch
the exceptions yourself. With a static constructor, you can (see Item 47):
static MySingleton2()
{
try
{
theOneAndOnly = new MySingleton2 ();
}
catch
{
// Attempt recovery here.
}
}
Static initializers and static constructors provide the cleanest, clearest way
to initialize static members of your class. They are easy to read and easy to
get correct. They were added to the language to specifically address the
difficulties involved with initializing static members in other languages.
Item 14: Minimize Duplicate Initialization Logic
Wr i t i n g con s t r u c to r s i s o f te n a rep e t i t ive t a s k . Ma ny d e ve l op e r s w r i te t h e
first constructor and then copy and paste the code into other constructors,
to satisfy the multiple overrides defined in the class interface. Hopefully,
you're not one of those. If you are, stop it. Veteran C++ programmers would
factor the common algorithms into a private helper method. Stop that,
too. When you find that multiple constructors contain the same logic, fac-
tor that logic into a common constructor instead. You'll get the benefits of
 
 
Search WWH ::




Custom Search