Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

C# - Constructors in C# with Example, Types of Constructor in C# with Example

Sep 25, 2013
Introduction:

Here I will explain what is constructor in c# with example, uses and types of constructors in c# default constructor, static constructor, copy constructor, parameterized constructor and private constructor examples in c#.net.  

Description:

In previous posts I explained use of virtual, override and new keyword with examples in c# method overloading and overriding, delegates example in c#, sealed class in c#, using statement in c#, OOPS examples in c# and many articles relating to interview questions in c#, asp.net, SQL server, JavaScript, jQuery. Now I will explain constructor in c#.net with example and different types of constructor in c#.net with example.

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.

Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.

Generally constructor name should be same as class name. If we want to create constructor in a class we need to create a constructor method name same as class name check below sample method for constructor


class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}

Types of Constructors

Basically constructors are 5 types those are

      1.    Default Constructor
      2.    Parameterized Constructor
      3.    Copy Constructor
      4.    Static Constructor
      5.    Private Constructor

Default Constructor

A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample()     // Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet-Suresh";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample();   // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


Welcome
Aspdotnet-Suresh

Parameterized Constructors

A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh");   // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


Welcome to Aspdotnet-Suresh

Constructor Overloading

In c# we can overload constructor by creating another constructor with same method name and different parameters like as shown below


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;

public Sample()     // Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample();   // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh");   // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
When we run above program it will show output like as shown below

Output


Hi, I am Default Constructor
Welcome to Aspdotnet-Suresh

Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj)     // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh");  // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


Welcome to Aspdotnet-Suresh

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.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.


using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()  // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}

Output


Welcome to Aspdotnet-Suresh

In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.


// it will works fine
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();
Important points of private constructor

-      One use of private construct is when we have only static member.
-      Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
-      If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

78 comments :

Anonymous said...

Very very nice article..
as always you do best

due to this article I have solved many douts regarding constuctor....
happy coding

Anonymous said...

is it possible to create private constructor ?waht will happen if we create private constructer

Unknown said...

hi...
what about private constructor?......

Anonymous said...

Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class. can u gv a example for ths

Unknown said...

Very nice article

Anonymous said...

nice article

Anonymous said...

Thanx 4 the details

Anonymous said...

very good ......... it more helpful for developer.

Bhavesh Bhuva said...

Very nice..
Thank..

Unknown said...

Good one, greate job....

Unknown said...

Gud one..you have written very short and specific things to understand clearly.

Anonymous said...

thanx

Unknown said...

Really very nice article

arun said...

Good article for constructors.

Anonymous said...

As all of your Articles, this also gives a clear understanding Mr.Suresh. Thanks

Sibin said...

It's good article.
http://sibinkt.blogspot.in/

sathya said...

very nice,Easy to understand the concepts.

Anonymous said...

Nice Article

Anonymous said...

really usefull...

Anonymous said...

Very nice

Anonymous said...

Really nice

Swarna said...

Really nice

Anonymous said...

Nice Article

Anonymous said...

Too gud :)

Anonymous said...

Very nice article.

Anonymous said...

Nice article,its very helpful

Anonymous said...

nice article :)

Anonymous said...

good article...easy to understand.

Anonymous said...

Nice article

Unknown said...

really nice

Unknown said...

Really nice articles. It's useful and easy to understand.

Thanks.

Unknown said...

Really nice articles. It's useful and easy to understand.

Thanks.

ANOOP SHARMA said...

Thanks..nice article...

ANOOP SHARMA said...

Thanks..nice article...

Unknown said...

Nice one With Detailed Explanation. thx :)

Unknown said...

Nice article...

Anonymous said...

good post.

Unknown said...

good article and easy to understand

Unknown said...
This comment has been removed by the author.
Unknown said...

good article

Anonymous said...

very useful meterial and the data is very clear

Unknown said...

Nice article..

Interviewfunda.com said...

Wow...
Nice explanations.......

Anonymous said...

sundarrrrrr

Nripendra Ojha said...

very very nice article, how and from where you learn these thing?
thanks for sharing very rare knowledge.

Kesavan said...

Good Article

Anjum Rizwi said...

Very nice to see the collectiive info of constructor.

Unknown said...

Nice Article Suresh!!
Please Explain below line..I think this line is incomplete or wrong Please explain

Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.

aravind said...

can u please check below statement:
it is not possible
If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

this is possible when:
if we want to create object of class even if we have private constructor then we need to have public with parameterised constructor along with Private constructor

aravind said...

can i create instance of class, which contains private and public constructor without parameters ? if it's not possible can u explain detail please.

Thanks,
Aravind

Unknown said...

Finally I found a site where I can study and Understand easily...ayushgupta2008@gmail.com

Unknown said...

nice artical

Anonymous said...

Good one

Unknown said...

Nice...explain constructor...thanks...

Varshas said...

Very good Article as always..thanks a lot

Anonymous said...

Too good, really very nice.... Thanks a lot :)

Unknown said...

Really i cleared all doubts in constructor...thnx

Unknown said...

great one !

Unknown said...

great article .. everything is cleared about Constructor.

Unknown said...

Great article ... it is very helpful for all.. thanks..

Unknown said...

Very useful one..but not arrange properly..make a list for your site..how can I get the subject what I want from your tutorial..make a list which we can see in side..and give us the link..

angularInfo said...

Nice Blog...

Unknown said...

nice work sir .....valuable information

Unknown said...

Very helpful. Thanks

Mohd Sarfraz said...

Really very nice article. After studying this article, I also cleared my many doubts about constructors.
thanks Suresh

Anonymous said...

Not bad article easy to understand.

Anonymous said...

good one..thanks for this

Software (Jobless) developers said...

very good one thanks a lot

Dipali said...

nice article..clear the concept of constructors..so easy to understand..so nice..

Unknown said...

nice and understandable article easy to learn for everyone thanks

Anonymous said...

Very well explaination sir..it's very useful to all c# beginners and easy to understand.Thanks so much sir to give your valuable time to write this article for all of us..

Anonymous said...

very helpful. :)

Girish said...

Very Good article.. Understand concept of all article thank you.

Girish said...

*constructor

Suraj said...

Nice Explanation Sir thank you so much.

Sir can you explain detail about how constructor allocate memory for class class. Please Sir.

Dharamvir Singh said...

Very good article.

Study said...

good constructor

Anonymous said...

very good article for constructor

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.