Вы находитесь на странице: 1из 10

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.

NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

Follow

ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL
HOME
ASP.NET
AJAX
GRIDVIEW
JAVASCRIPT
SQL
JQUERY
OOPS CONCEPTS
INTERVIEW QUESTIONS
Server,Ajax,SSRS, XML examples
CONTACT
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

TRACE MOBILE

FORUMS

Search This Site

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


with Example

Search

By: Suresh Dasari Sep 25, 2013


Categories: C#.Net , Interview Questions , OOPS Concepts

Introduction:
Here I will explain what is constructor in c#with example, uses and types of constructors in c# default

87

constructor, static constructor, copy constructor, parameterized constructor and private constructor
examples in c#.net.

Like
Tweet

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

25

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.

2
Share

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 dont
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

FollowUS
Follow

class SampleA
{

25

public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}
Types of Constructors
Basically constructors are 5 types those are

Select Language
Select
Language

Powered by

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

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

Recent Posts

Translate

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

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();
}
}

Get Latest articles in your inbox for free.


Enter your email address:

}
When we run above program it will show output like as shown below

Subscribe

Output

Aspdotnet-Suresh

Welcome
Aspdotnet-Suresh

+1
+ 1,999

Parameterized Constructors

Aspdotnetsuresh
14,877

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();
}

Tags

Asp.net

JQuery General C#.Net


VB.NET Code Snippets Javascript SQL Server
Gridview JQuery Plugins Errors Interview
Questions Ajax Fileupload DropdownList c# AngularJS
Google API JSON validations Google MAPS
DatePicker CSS Windows Application IISServer
Authentication AutoComplete CheckBox Crystal
Reports Modalpopup ExcelSheet OOPS Concepts
SharePoint HTML Membership ExportGridviewData
jQuery UI XML SendMail UpdatePanel WebService
AjaxModalPopupExtender Google Maps API InternetTips
SlideShow WCF Menu Progressbar SQL Joins ToolTip

asp.net mvc DataGridview YouTube web.config DataList

LightBoxEffect RDLC Report RadioButtonList loading Image


mvc

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

Charts

CheckBoxList

Dynamic

Controls

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

When we run above program it will show output like as shown below

EncryptionandDecryption Facebook Global.asax Repeater


SSRS Twitter Visual Studio Windows Service jQuery Menu

Output

Access Database Accordion Menu AjaxAsyncFileUpload


Blog Statistics Fixed Header on Scroll IEnumerable ListBox
Polymorphism

Welcome to Aspdotnet-Suresh

UI

setTimeOut

Grid

360

ZIP

UNZIP

Degree

AjaxAutoCompleteExtender

Files

setInterval

View

AjaxTabContainer

Plugins

Average

rating

Captcha Cookie Flip Effect HTML5 KeyBoard Key Codes

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

Linkedin MultilineTextbox News Ticker in jQuery PDF Viewers


Product Reviews Resize Image Reviews SQL Constraints SQL
Server

2008

Bookmark

R2 Session

Plugins

Timeout SiteMap Social

ThumbnailsGeneration

UserName

Media
Check

Visitors Count app.config jQuery Cookie jQuery Media Plugins 3TierArchitecture ADO.NET AbstractVsInterface ActiveDirectory
Advertise Ajax Calendarextender Ajax ConfirmbuttonExtender

using System;

AjaxAccordionControl

namespace ConsoleApplication3

AjaxCollapsiblePanelControl

{
class Sample

AjaxCalendarExtender
AjaxDragPanelExtender

AjaxPasswordStrength AjaxRatingControl AjaxSlideshowExtender


Arraylist Assembly Authorization Bootstrap Chatting Plugins
CodingStandards Custom Right Click Menu Dapper DataGrid

Error Log Forums Generic List Google Charts Gzip Compression

public string param1, param2;

IP Address ImportContacts LINQ MCC Award MVP Award


Northwind Database Panorama Image Viewer Plugins Print DIV

public Sample() // Default Constructor


{

Projects

QueryString

RSSFeeds

Read/Write

text

file

ReadOnlyValues RichTextBox Scrollbar Setup File Spell Checker


Testimonial Example Testing Trace Mobile Number Try Catch

param1 = "Hi";

VBScript Virtual Keyboard WPF Windows 8 bulk copy contactus

param2 = "I am Default Constructor";

delegates dynamically page create generate script jQuery Audio

Plugins jQuery Mobile jQuery Video Plugins jqGridview scroll

public Sample(string x, string y) // Declaring Parameterized constructor with Parameters

top/bottom of div slider from folder sorting tree view

{
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)
{

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

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 its 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();
}
}
}

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

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();

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

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.

25

Subscribe by RSS

Subscribe by Email

Follow

39 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

September 25, 2013 at 11:56 PM


Anonymous said...

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

September 26, 2013 at 2:51 AM


Amol Sonavane said...

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

September 26, 2013 at 4:12 AM


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

October 4, 2013 at 12:28 PM


sunil srinivas said...

Very nice article

May 1, 2014 at 12:33 AM


Anonymous said...
nice article

May 6, 2014 at 11:39 PM

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples
Anonymous said...

Thanx 4 the details

May 7, 2014 at 3:42 AM


Anonymous said...

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

May 7, 2014 at 4:54 PM


Bhuva Bhavesh said...

Very nice..
Thank..

May 30, 2014 at 4:59 AM


Sunil Gaded said...

10

Good one, greate job....

June 2, 2014 at 12:22 AM


Rishi Trivedi said...

11

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

June 17, 2014 at 5:41 AM


Anonymous said...

12

thanx

June 23, 2014 at 1:05 AM


Muhammad Jafar said...

13

Really very nice article

August 7, 2014 at 11:35 PM


arun said...

14

Good article for constructors.

August 8, 2014 at 11:47 PM


Anonymous said...

15

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

September 15, 2014 at 7:22 AM


Sibin K T said...

16

It's good article.


http://sibinkt.blogspot.in/

November 6, 2014 at 3:52 AM


sathya said...

17

very nice,Easy to understand the concepts.

November 17, 2014 at 11:38 PM


Anonymous said...
Nice Article

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

18

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples
December 1, 2014 at 12:10 AM
Anonymous said...

19

really usefull...

December 1, 2014 at 8:06 AM


Anonymous said...

20

Very nice

December 18, 2014 at 5:49 PM


Anonymous said...

21

Really nice

January 19, 2015 at 10:28 AM


Swarna said...

22

Really nice

January 19, 2015 at 10:30 AM


Anonymous said...

23

Nice Article

February 10, 2015 at 10:02 PM


Anonymous said...

24

Too gud :)

March 7, 2015 at 7:17 AM


Anonymous said...

25

Very nice article.

March 14, 2015 at 12:25 AM


Anonymous said...

26

Nice article,its very helpful

April 1, 2015 at 6:20 AM


Anonymous said...

27

nice article :)

April 6, 2015 at 1:42 AM


Anonymous said...

28

good article...easy to understand.

April 8, 2015 at 3:01 AM


Anonymous said...

29

Nice article

April 9, 2015 at 8:48 PM


sikha rath said...
really nice

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

30

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples
May 8, 2015 at 5:36 AM
Vikash Shrivastava said...

31

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


Thanks.

May 9, 2015 at 1:50 PM


Vikash Shrivastava said...

32

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


Thanks.

May 9, 2015 at 1:58 PM


ANOOP SHARMA said...

33

Thanks..nice article...

August 5, 2015 at 11:01 AM


ANOOP SHARMA said...

34

Thanks..nice article...

August 5, 2015 at 11:01 AM


Happy karthik said...

35

Nice one With Detailed Explanation. thx :)

August 6, 2015 at 8:44 AM


Rupesh Kumar said...

36

Nice article...

August 9, 2015 at 11:01 AM


neeraj pokhariyal said...

37

nice

August 16, 2015 at 5:35 AM


Bhavesh Patel said...

38

good post.

August 19, 2015 at 3:30 AM


Shirisha Dindigala said...
good article and easy to understand

August 24, 2015 at 5:01 AM

Give your Valuable Comments

Comment as:

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

39

C# - Constructors in C# with Example, Types of Constructor in C# with Example - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,SSRS, XML examples

Publish

Preview

Newer Post

Notify me

Home

Older Post

Subscribe to: Post Comments ( Atom )

Other Related Posts


Interview Questions in ASP.NET,C#.NET,SQL Server,.NET Framework
Asp.net insert, Edit, update, delete data in gridview
3 tier architecture example in asp.net with C#
Introduction to Object Oriented Programming Concepts (OOPS) in C#.net
Simple login form example in asp.net Check Username and Password availability in database
Introduction to WCF - WCF tutorial | WCF Tutorial - Windows Communication Foundation | WCF Example
| WCF Sample code in asp.net 3.5 | Basic WCF Tutorial for Beginners
how to insert images into database and how to retrieve and bind images to gridview using asp.net (or)
save and retrieve images from database using asp.net
jQuery 360 Degrees Image Display Plugins Examples with Tutorial
Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice in
asp.net or how to create webservice and how to use webservice in asp.net
Best Login Page Design in HTML, CSS with Source Code

2015 Aspdotnet-Suresh.com. All Rights Reserved. Hosted By Hostgator


The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.

http://www.aspdotnet-suresh.com/2013/09/csharp-constructor-example-types-of-constructor-in-csharp.html[08/09/2015 20:16:24]

Вам также может понравиться