Type Constructor Design
This page is specific to:.NET Framework Version:2.03.03.54.0
.NET Framework Developer's Guide
Type Constructor Design

A type constructor is used to initialize static data in a type. It is called by the common language runtime (CLR) before any instances of the type are created. Type constructors are static (Shared in Visual Basic) and cannot take parameters.

The following guidelines help ensure that your use of static constructors complies with best practices.

Do make type constructors private.

A type constructor, also called a class constructor or static constructor, is used to initialize a type. The CLR calls the type constructor before the first instance of the type is created or any static members on the type are called. If a type constructor is not private, it can be called by code other than the CLR. Depending on the operations performed in the constructor, this can cause unexpected behavior.

Do not throw exceptions from type constructors.

If a type constructor throws an exception, the type is not usable in the application domain where the exception was thrown.

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.

The following code example demonstrates a design that cannot be optimized.

Public Class BadStaticExample
    Shared runId as Guid
    Shared Sub New()
        runId  = Guid.NewGuid()
    End Sub
    ' Other members...
End Class


The following code example can be optimized.

Public Class GoodStaticExample
    Shared runId as Guid = Guid.NewGuid()
    ' Other members...
End Class


Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also

Concepts

Other Resources

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View