An instance constructor implements code to initialize the instance of the class. A static constructor implements code to initialize the class itself when it is first loaded.
Static constructors have the following properties: · A static constructor does not take access modifiers or have parameters. · A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. · A static constructor cannot be called directly. · The user has no control on when the static constructor is executed in the program. · A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. · Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Assume that a class, Class1, has both instance and static constructors. Given the code below, how many times will the static and instance constructors fire? Answer:
Class1 c1 = new Class1(); Class1 c2 = new Class1(); Class1 c3 = new Class1(); by definition, a static constructor is fired only once when the class is loaded. An instance constructor on the other hand is fired each time the class is instantiated. So, in the code given above, the static constructor will fire once and the instance constructor will fire three times.
|
| Author: siva prasad 07 May 2008 | Member Level: Silver Points : 2 |
good one
|