CSharp - Add Constructors to class

Introduction

We can use a static constructor to initialize any static data.

static constructor can only run once.

We cannot call a static constructor directly.

The static constructor will be called automatically in either of these scenarios:

  • Before the creation of an instance of a type.
  • When we reference a static member in our program.

Demo

using System;
class A//from w w  w.ja  va 2  s. c  o m
{
    static int StaticCount = 0, InstanceCount = 0;
    static A()
    {
        StaticCount++;
        Console.WriteLine("Static constructor.Count={0}", StaticCount);
    }
    public A()
    {
        InstanceCount++;
        Console.WriteLine("Instance constructor.Count={0}",
         InstanceCount);
    }
}
class Program
{
    static void Main(string[] args)
    {
        A obA = new A();//StaticCount=1,InstanceCount=1
        A obB = new A();//StaticCount=1,InstanceCount=2
        A obC = new A();//StaticCount=1,InstanceCount=3
    }
}

Result

Analysis

A type can have only one static constructor.

It must be parameterless and it does not accept any access modifier.

static field initializers run prior to a static constructor in the declaration order.

In the absence of a static constructor, field initializers execute just before the type is used.

static constructors can be useful to write log entries.

Related Example