It’s a quick article. In a technial interview, panel has asked me about the static constructors and how and when static constructors will be called etc.
He wrote a program to extract more idea from me through. I recreated the program to explain about it. Before going further I will fill in details about STATIC constructors.
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
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.
Here is the program logic my interviewer has asked me
[code lang=”c-sharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp02
{
class Program
{
static void Main(string[] args)
{
TestStatic objTestStatic1 = new TestStatic();
TestStatic objTestStatic2 = new TestStatic();
TestStatic objTestStatic3 = new TestStatic();
Console.Read();
}
}
public class TestStatic
{
public static int iStat = 0;
public int iNorm = 0;
//Static Contructor. Will be initialized when first time class object is created or static object inside the class are referenced.
//(•A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.)
static TestStatic()
{
iStat = 100;
Console.WriteLine(String.Format("** STATIC :: Constructor :: – TestStatic – iStat = {0} **", iStat));
}
public TestStatic()
{
iNorm = 1;
Console.WriteLine(String.Format("** STANDARD :: Constructor :: – TestStatic – iNorm = {0} **", iNorm));
}
}
}
[/code]
He asked me to write down the values of iStat and iNorm variables after each object creation. As specified about the static constructor functioning, it will be called only once, automatically before the first instance is created or any static members are referenced. So iStat remains 100(once only initialized), iNorm remain 1, on each object creation.
The resultant output will be.
Discover more from Cloud Distilled ~ Nithin Mohan
Subscribe to get the latest posts sent to your email.