Share via


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
public class BadStaticExample
{
    static Guid runId;
    static BadStaticExample()
    {
        runId  = Guid.NewGuid();
    }
    // Other members...
}

The following code example can be optimized.

Public Class GoodStaticExample
    Shared runId as Guid = Guid.NewGuid()
    ' Other members...
End Class
public class GoodStaticExample
{
    static Guid runId  = Guid.NewGuid();
    // Other members...
}

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

Constructor Design

Other Resources

Member Design Guidelines
Design Guidelines for Developing Class Libraries