Interview : Static Constructor in class

Posted: October 10, 2015 in Interview, OOPS Q&A
Tags:

Q1 : Static Constructor kakey bola hoy ?

A1 : Amra jokhun static class variable niye kaj kori tokhun oi static data k initialise korar jonno static constructor use kora hoy.

MSDN e bola aachey :

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

er maney holo static class ekta class constructor, r eder k tokhun e call kora hoy

  1. when we are creating any instance
  2. when the class is refereed somewhere.

Q2 : Static member amra kano use kori ? if inline initialization is possible.

Code : 

public static class BasicClass
{
 static int i = 0;
 static BasicClass()
 {
 i = 10;
 }

 public static void Temp()
 {
 //some code
 }


 public static void Temp1()
 {
 //some code
 }
}

Inside this I have a static variable i which is initialized to 10 when it is first called. So basically it may be the purpose of a static constructor but the same thing can be achieved without declaring a static constructor by initializing the

static int i = 10

which serves the same purpose that is gets initialized only once. Then why do we need a static constructor?

A2 : Ami  jodi oi class ta k compile kori into an assembly. r tar por ILSpy kimba oi similar type er tool diye disassemble kori tobe dekha jabe j somosto static member initialization are done by static constructor itself only.

For instance, the following C# code:

public static class BasicClass
{
    static int i = 10;
}

Will produce IL equivalent to:

public static class BasicClass
{
    static int i;

    static BasicClass()
    {
        i = 10;
    }
}

In other words, direct initialization is only syntactic sugar provided by the C# compiler. Under the hood, a static constructor is still implemented.

ebar dekha galo j oi integer variable er value ta ami direct na set kore database theke set korchi. tokhun amar code ta thik kichu ta ei rokhm howa uchit :

static BasicClass()
{
    using (SomeConnection con = Provider.OpenConnection())
    {
        try
        {
            // Some code here
        }
        catch
        {
            // Handling expeptions, setting default value
            i = 10;
        }
    }
}

Now it is not possible to declare and initialize your static field, you’re better served using a static constructor.

Aro ekta important bapar next para te highlighted kora hoychey :

One factor not yet mentioned is that there is a semantic difference between having a static constructor (written using constructor syntax) call foo() versus having a static field initializer do so. In particular, if a type has a static constructor written using constructor syntax, that constructor is guaranteed to be invoked the first time code which would “use” that type is executed; it will not be invoked before that, nor will it be invoked if the type isn’t used. By contrast, although .NET guarantees that a type’s static field initializers will run before any of its static fields are accessed, and will not run more than once, .NET is free to run such static initializers the first time it thinks a type might get used. Consider for example:

if (someCondition())
  for (i=0; i<100000000; i++)
    someClass.someStaticField++;

If when the Just-In-Time compiler encounters the above code, someClass has never been used, and it has a constructor declared using static constructor syntax, the resulting machine code will be something like:

if (someCondition())
  for (i=0; i<100000000; i++)
  {
    if (someClass.hasBeenInitialized)
      someClass.runConstructor();
    someClass.someStaticField++;
  }

performing the if-check within the loop. By contrast, if there had been field initializations but no constructor-style declaration, the JIT would likely perform the static construction of someClass before running the code, thus eliminating the need to include the if check within it.

Q3 : Usage of static constructors ?

A3 : Usage:

1. 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.

2. Suppose we have a static class that uses database access then a static constructor is a handy place to initialize that database connection, because it means that the connection will get created right before it is first needed.

3. As you know each object occupies some space in memory. But by using static constructor we can reduce it. That means increase in performance.

NOTE : A static constructor does not take access modifiers or have parameters and can’t access any non-static data member of a class.

Q4 : Static Constructor ki overload kora jaye ? explain ?

A4 : Not possible because Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.

Q5 : Why there should be no access modifier to it. ?

A5 : Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it

Q6 : Ekta non static class e static constructor er ki kaj ?

a non-static class can have a static constructor:

public class Thing
{
    public Thing()
    {
        Console.WriteLine("non-static");
    }

    static Thing()
    {
        Console.WriteLine("static");
    }
}

And when you initialize an instance of Thing the static constructor gets called first.

Output:

static

non-static

A6 : Static fields or members are usually not associated with instances, rather they are more related with Types regardless wheather the class is static or non static.

Q7 : Instance constructor er por static constructor call hochey ? eta ki sombob and how ?

http://stackoverflow.com/questions/4150151/static-constructor-called-after-instance-constructor?rq=1

Resources :

Static constructors, part one

Leave a comment