Sunday, September 18, 2011

Static constructor

Que: Where static members are allocated?
Ans: Data Segment.
Here is memory model which shows static member's location in memory -

Que: Is it possible to make constructor private?
Ans: yes. It is useful if we know that a class has only static member in it.Or when we want to control object creation with its constructor(Ex. Singleton pattern)

Que: Is it possible to have constructor static?
Ans: Yes. Here is the signature:
class A
{
public static int a;
    static A()
    {
       a = 5;
    }
}
It doesn't have any access modifier in it. It is class level.

Que: What is the use of static constructor?
Ans: It is used to initialize static variables in the class or to perform some action which needs to be performed only once.

Que: When is static constructor called?
Ans:  It is called when we try to create an object of class or when we try to access the static variable in class(whichever comes first.).

Que: What if the static constructor throws some exception?
Ans: If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

No comments:

Post a Comment