Information Technology Reference
In-Depth Information
Static Constructors
Constructors can also be declared static . While an instance constructor initializes each new
instance of a class, a static constructor initializes items at the class level. Generally, static con-
structors initialize the static fields of the class.
￿
Class level items need to be initialized
-
Before any static member is referenced
-
Before any instance of the class is created
￿
Like instance constructors
-
The name of the static constructor must be the same as the name of the class.
-
The constructor cannot return a value.
￿
Unlike instance constructors
-
Static constructors use the static keyword in the declaration.
-
There can only be a single static constructor for a class, and it cannot have
parameters.
-
Static constructors cannot have accessibility modifiers.
The following is an example of a static constructor. Notice that its form is the same as that
of an instance constructor, but with the addition of the static keyword.
class Class1
{
static Class1 ()
{
... // Do all the static initializations.
}
...
Other important things you should know about static constructors are the following:
￿
A class can have both static and instance constructors.
￿
As with static methods, a static constructor cannot access non-static members of its
class, and therefore cannot use the this accessor.
￿
Static constructors cannot be called by your program. They are called automatically by
the system
-
Before any instance of the class is created
-
Before any static member of the class is referenced
Search WWH ::




Custom Search