Information Technology Reference
In-Depth Information
The final reason to move initialization into the body of a constructor is to
facilitate exception handling. You cannot wrap the initializers in a try
block. Any exceptions that might be generated during the construction of
your member variables get propagated outside your object. You cannot
attempt any recovery inside your class. You should move that initializa-
tion code into the body of your constructors so that you implement the
proper recovery code to create your type and gracefully handle the excep-
tion (see Item 47).
Member initializers are the simplest way to ensure that the member vari-
ables in your type are initialized regardless of which constructor is called.
The initializers are executed before each constructor you make for your
type. Using this syntax means that you cannot forget to add the proper
initialization when you add new constructors for a future release. Use ini-
tializers when all constructors create the member variable the same way;
it's simpler to read and easier to maintain.
Item 13: Use Proper Initialization for Static Class Members
Yo u k n o w t h a t y o u s h o u l d i n i t i a l i z e s t a t i c m e m b e r v a r i a b l e s i n a t y p e
before you create any instances of that type. C# lets you use static initial-
izers and a static constructor for this purpose. A static constructor is a spe-
cial function that executes before any other methods, variables, or
properties defined in that class are accessed for the first time. You use this
function to initialize static variables, enforce the singleton pattern, or per-
form any other necessary work before a class is usable. You should not use
your instance constructors, some special private function, or any other
idiom to initialize static variables.
As with instance initialization, you can use the initializer syntax as an alter-
native to the static constructor. If you simply need to allocate a static mem-
ber, use the initializer syntax. When you have more complicated logic to
initialize static member variables, create a static constructor.
Implementing the singleton pattern in C# is the most frequent use of a
static constructor. Make your instance constructor private, and add an ini-
tializer:
public class MySingleton
{
private static readonly MySingleton theOneAndOnly =
new MySingleton ();
 
 
Search WWH ::




Custom Search