Thursday 6 November 2014

Static Constructor in C#

Introduction:

Here I will explain what is static constructor in c# with example. Static constructor in c# is used to create static fields of the class and to write the code that needs to be executed only once.

Description:
Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.

Static Constructor
When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}


When we run above program we will get output like as shown below
Output
Static Constructor
Sample Instance Constructor
Sample Instance Constructor

Importance points of static constructor

-      Static constructor will not accept any parameters because it is automatically called by CLR.
-      Static constructor will not have any access modifiers.
-      Static constructor will execute automatically whenever we create first instance of class
-      Only one static constructor will allowed.

I hope it helps to know about static constructor. 

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives