Type Constructor:
a. Type constructor is also termed as class/static constructor or type initializers.
b. This constructor gets called when the class gets loaded into the memory and before any of its members are accessed or called.
c. Type constructors can only initialize the static fields in the class.
d. There can be only one type constructor per class and it cannot use vararg (variable argument) calling convention.

Instance Constructor:
a. Instance Constructors are executed when an instance or an object of a class is created.
b. This constructor gets executed after the class is loaded and before any of its members is accessed.
c. Instance constructors can initialize both static and instance fields of the class.
d. There can be multiple overloaded instance constructors with parameters. The return type must be void.

Lets see an example to understand better,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Constructors
{
class Program
{
class myClass
{
public static int _static; //static field.
public int _nonStatic; //non-static field.

//Type constructor
static myClass()
{
//initializes only static fields.
_static = 20;
//_nonStatic = 30; //gives error
}

//Instance constructor
public myClass()
{
//initializes both static and non-static fields.
_static = 30;
_nonStatic = 40;
}
}

static void Main(string[] args)
{
Console.WriteLine(myClass._static); //prints 20;

myClass _myClass = new myClass();
Console.WriteLine(myClass._static); //prints 30;
Console.WriteLine(_myClass._nonStatic); //prints 40;
}
}
}


Enjoy coding.

0 comments