Please enable Javascript to correctly display the contents on Dot Net Tricks!

Constructor in C Sharp

  Author : Shailendra Chauhan
Updated On : 23 Feb 2014
Total Views : 105,572   
Support : All
 

In C#, Constructors are the special types of methods of a class which get executed when it's object is created. Constructors are responsible for object initialization and memory allocation of its class. There is always at least one constructor in every class. If you don't write a constructor in class, C# compiler will automatically provide one constructor for that class, called default(parameter less) constructor.

Types of Constructor

Generally, constructors are of three types. But C# doesn't support copy constructor.

  1. Default Constructor(Non-Parametrized constructor)

  2. Parametrized Constructor

  3. Copy Constructor

Default Constructor with example

 using System; 
Class example1 {
 int roll; float marks;
 public example1() //constructor
{ 
 roll=0; 
 marks=0.0; 
 }
 // other members 
}

The above mentioned constructor example1() doesn't take any argument therefore it is an example of default/non-parameterized constructor. With this type of constructor, the object will be created as follows :

 example1 obj1 = new example1 (); 

Parameterized Constructor with example

 Class example2 
{ 
int roll; 
float marks;
public example2(int a, float b)//constructor
{ 
 roll = a; 
 marks = b; 
 } 
//other members
 }

The above defined constructor takes two arguments one int and other float to initialize instance members roll and marks for the newly created object and therefore it is called parameterized constructor. With this type of constructor, the object will be created as follows :

 example2 obj = new example2( 5 , 33.05F); 

Constructor Overloading

In C# it possible to overload the constructors, it means we can have more than one constructor with different parameters

using System; 
public Class OverloadConst 
{ 
public OverloadConst() 
{ 
//Default constructor 
} 
public OverloadConst(int age) 
{ 
//Single parameter constructor 
} 
public OverloadConst(int age, string name) 
{ 
//two parameter constructor 
} 
} 

Now, following are the ways through which we can instantiate the object

OverloadConst obj=new OverloadConst() ; //Default constructor will get called
OverloadConst obj=new OverloadConst(33) ; //Single parameter constructor will get called
OverloadConst obj=new OverloadConst(35,"asif") ; //Two parameters constructor will get called 

In above example you have seen that constructor overloading is completely governed by the rule of overloading , i.e, overloading must need two or more method to be different in terms of method signature.

Now, one question here for you , can we have two constructor like this ?

using System;
public Class question {
 static question() 
{ 
// initialize static member only.
} 
public question() 
{ 
//codes for the first derive class constructor. 
}
 } 

The answer to this question is on hold unto the discussion over static constructor.

Many a place you might have been read that a constructor can't be declared as static, this is not true for C# there can be a static constructor in C# .However, it is true for earlier language like C++ .

Static Constructors

Static constructor is a special constructor that gets called before the first object of the class is created. It is used to initialize any static data, or to perform a particular action that needs performed once only.

The time of execution of static constructor is not known but it is definitely before the first object creation - may be at the time of loading assembly.

//Example1
using System;
public Class abc
 {
 static abc() 
{ 
// initialize static members only.
 }
 // other methods here.
 }
// Example2
using System;
public class MyStaticClass 
{ 
static int count; 
static MyStaticClass() 
{ 
count = 0; 
Console.WriteLine("Static class is initialized"); 
} 
public static void MyMethod(string name) 
{ 
Console.WriteLine("Static class is initialized " + name); 
} 
}
MyStaticClass.MyMethod("John") ; //method call
//constructor will be called automatically
Output:
Static class is initialized Hello John 

Key points about static constructor

  1. It can only access the static member(s) of the class.

  2. Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.

  3. There should be no parameter(s) in static constructor.

    Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it.

  4. Only one static constructor is allowed.

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

  5. There should be no access modifier to it.

    Reason: 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

Now, the answer of the question I asked earlier for the following class definition that - can we have two constructors like this?

 using System; 
public Class question {
 static question()
 { 
//initialize static member only.
 } 
public question() 
{ 
// codes for the first derive class constructor. 
 }
 }

Ans : Yes, this is perfectly valid even if it doesn't match with the rule of overloading concept. The only reason of being it valid is that the time of execution of the two constructors are different, (i) static question() at the time of loading the assembly and (ii) public question() at the time of creating object.

Private Constructor

A private constructor is a special instance constructor used in class that contain static member only. If a class have one or more private constructor and no public constructor then other classes (except nested classes ) are not allowed to create instance of this class. Means, we can neither create the object of the class nor it can be inherit by other class.

The public constructor can access the private constructors from within class through constructor chaining.

 using System; 
public Class demo {
private demo() 
{ 
 Console.WriteLine("This is no parameter private constructor");
 }
 public demo(int a):this() 
{ 
Console.WriteLine("This is one parameter public constructor");
 }
 // other methods
 }

The object of the class can be created as :

 demo obj = new demo(10) ; //it will work fine. 

But defining object like this won't work.

 demo obj = new demo() ; // error of inaccessibility will be occur.

Key points about private constructor

  1. one use of private construct is when we have only static member.

  2. It provide implementation of singleton class pattern

  3. Once we provide constructor (private/public/any) the compiler will not add the no parameter public constructor to any class.

  4. If we still want to make object of the class having private constructor. We can have a set of public constructor along with the private constructor.

Summary

That’s all from my side I hope the article will help you a lot to understand the nature of a constructor. Comments, criticism and suggestions are always welcome.

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri     6:30 AM-7:30 AM IST

3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (09:30 AM-11:00 AM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+